Jav*_*gFu 3 javascript object instance
我正在尝试在命名空间中创建一个函数,它将为我提供一个新的对象实例.
尝试执行以下操作时出现语法错误:
var namespace = {
a : function(param){
this.something = param;
},
a.prototype.hi = function(){
alert('hi');
},
b : function(){
var t = new a('something');
}
};
Run Code Online (Sandbox Code Playgroud)
这样做的正确语法是什么?是不是可以在namespace对象内做?我不想先声明命名空间.谢谢
我不想先声明命名空间.
你可以做这样奇怪的事情:
var namespace = {
init: function() {
a.prototype.whatever = function(){};
},
a: function(x) {
this.x = x;
}
}
namespace.init();
var myA = new namespace.a("x");
Run Code Online (Sandbox Code Playgroud)
但是,如果要封装所有内容,为什么不尝试模块模式呢?它更干净:
var namespace = (function() {
function a() {};
function b(name) {
this.name = name;
};
b.prototype.hi = function() {
console.log("my name is " + this.name);
}
return {
a: a,
b: b
}
})();
Run Code Online (Sandbox Code Playgroud)