对象和数组不是应该添加到原型中的东西除非您想与所有实例共享它们。
一旦您希望这些对象的属性对于每个实例都不同,您必须将构造函数(或任何其他函数)中的对象分配给特定实例:
this.subClass = {
foo: true
// potentially other properties
};
也就是说,原型中可能有一个“默认”对象可能是合理的,但你不应该写它。
在构造函数中分配对象不会重复代码,并允许您为每个实例单独更改它。
更新:
如果您不想更改原始构造函数,您可以在原型中添加一个新函数并在实例化对象时调用它:
MyClass.prototype.init = function() {
this.subClass = {
//...
};
};
和
var obj = new MyClass();
obj.init();
或者你真的创建了一个新的构造函数:
function MySubClass() {
MyClass.apply(this, arguments);
// now create that object for each instance
this.subClass = {
foo: someValue
};
}
inherits(MySubClass, MyClass);
其中inherits 定义为:
function inherits(Child, Parent) {
var Tmp_ = function() {};
Tmp_.prototype = Parent.prototype;
Child.prototype = new Tmp_();
Child.prototype.constructor = Child;
}
然后您将使用MySubClass 而不是MyClass 来创建实例。