试图在构造函数中构建一个具有内部属性的对象,该函数将数组与使用相同构造函数创建的所有对象保持一致。
我认为最好的方法是在对象初始化时使用闭包,这就是我尝试解决这个问题的方法:
function myObject (name){ this.name=name; this.allInstances = []; } myObject.ptototype = { init : function(){ return function(){this.allInstances.push(this.name)}; }(), } object1 = new myObject("object1"); object2 = new myObject("object2"); console.log(object1.allInstances); // should print ["object1", "object2"]
有人知道如何实现吗?这可能吗?
我特别想获得一个仅使用函数构造函数和原型(prototype)来实现的解决方案。
我知道如何通过将属性推送到外部数组来解决这个问题,例如:
var allInstances = []; function myObject (name){ this.name=name; allInstances.push(this.name); } console.log(allInstances)
最佳答案
将数组作为属性放在原型(prototype)
上,它将在所有实例之间共享:
function myObject(name) {
this.name = name;
this.allInstances.push( this.name );
}
myObject.prototype.allInstances = [];
object1 = new myObject("object1");
object2 = new myObject("object2");
console.log(object1.allInstances); // ["object1", "object2"]
或者,如果您希望 Array 受到更多保护,请使用模块模式,并在原型(prototype)上包含一个函数以返回 Array。
var myObject = (function() {
var allInstances = [];
function func(name) {
this.name = name;
allInstances.push( this.name );
}
func.prototype.getAllInstances = function() { return allInstances; };
return func;
})();
object1 = new myObject("object1");
object2 = new myObject("object2");
console.log(object1.getAllInstances()); // ["object1", "object2"]
关于javascript - 包含在 Javascript 中使用相同函数构造函数创建的所有对象实例的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324587/