首先,抱歉我缺乏术语.
如果我有一个构造函数
function myObject(name,value){
this.name = name;
this.value = value;
}
我从中制作了一些物品
var One = new myObject("One",1);
var Two = new myObject("Two",2);
我可以遍历从myObject类创建的每个新Object,而不将每个新Object放入一个数组中吗?
是否可以将Instantly调用函数添加到将Object添加到数组中的构造函数中?
例如
function myObject(name,value){
this.name = name;
this.value = value;
this.addToArray = function(){
theArray.push(this); // this is the IIFE
}();
}
这样,任何创建的新对象都会立即运行此函数并添加到数组中.
这可能吗? (显然当前语法不起作用)
编辑回到这一年后,我可以告诉你,这是可能的.你只需在构造函数中调用函数,如下所示:
function myObject(name,value){
this.name = name;
this.value = value;
this.addToArray = function(){
theArray.push(this);
};
this.addToArray();
}
这是JSfiddle中的一个示例,在实例化时将每个对象推送到一个数组中,然后直接从数组调用每个对象的.speak()方法.
https://jsfiddle.net/Panomosh/8bpmrso1/
解决方法
不使用数组,你不能,它不是它的使用方式.
但是你可以做的是监视在myObject类的静态成员中创建的每个实例
function myObject(name,value){
this.name = name;
this.value = value;
this.watch();
}
myObject.prototype.watch = function () {
if (myObject.instances.indexOf(this) === -1) {
myObject.instances.push(this);
}
};
myObject.prototype.unwatch = function () {
myObject.instances.splice(myObject.instances.indexOf(this),1);
};
myObject.instances = [];