为什么 setInterval 添加的函数停止执行?
Why function added by setInterval stops executing?
我有代码:
function Creature(id){
self = this;
this.lifecycle = {};
this._cid = id;
this.lifeInterval = setInterval(function(){
_.each(self.lifecycle,function(lifecycleItem){
if (lifecycleItem.active) { lifecycleItem.execute() };
});
},1000);
}
Creature.prototype.run = function() {
self = this;
this.lifecycle.run = {
active : true,
execute : function(){
console.log(self.cid + " is running");
}
}
};
如果我尝试创建名为 sampleCreature 的新变量,并执行其方法 运行():
var sampleCreature = new Creautre(1);
sampleCreature.run();
在控制台中出现一条消息:
1 is running
每秒重复一次。没关系。
但是,如果我添加具有任何其他名称的新生物 - 控制台中的消息将停止重复,直到我再次对其中一个生物使用方法 运行()。
还有另一个问题 - 在第一个 Creature 上执行方法 运行() 会停止在其他 Creature 上执行此方法。
self
是全局的而不是局部的。添加 var
这样它们就不会相互覆盖。
self = this;
需要
var self = this;
我有代码:
function Creature(id){
self = this;
this.lifecycle = {};
this._cid = id;
this.lifeInterval = setInterval(function(){
_.each(self.lifecycle,function(lifecycleItem){
if (lifecycleItem.active) { lifecycleItem.execute() };
});
},1000);
}
Creature.prototype.run = function() {
self = this;
this.lifecycle.run = {
active : true,
execute : function(){
console.log(self.cid + " is running");
}
}
};
如果我尝试创建名为 sampleCreature 的新变量,并执行其方法 运行():
var sampleCreature = new Creautre(1);
sampleCreature.run();
在控制台中出现一条消息:
1 is running
每秒重复一次。没关系。
但是,如果我添加具有任何其他名称的新生物 - 控制台中的消息将停止重复,直到我再次对其中一个生物使用方法 运行()。
还有另一个问题 - 在第一个 Creature 上执行方法 运行() 会停止在其他 Creature 上执行此方法。
self
是全局的而不是局部的。添加 var
这样它们就不会相互覆盖。
self = this;
需要
var self = this;