[英]Why function added by setInterval stops executing?
I've got code: 我有代码:
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");
}
}
};
If I try to create new variable called for example sampleCreature, and execute its method run(): 如果我尝试创建名为sampleCreature的新变量,并执行其方法run():
var sampleCreature = new Creautre(1);
sampleCreature.run();
In console appears a message: 在控制台中出现一条消息:
1 is running 1正在运行
which repeating each second. 每秒重复一次。 It is ok. 没关系。
But if I add new creature with any other name - message in console stop repeating until I again use method run() on one of Creature. 但是,如果我添加任何其他名称的新生物-控制台中的消息停止重复,直到我再次对Creature之一使用run()方法。
And another problem - executing method run() on first Creature stops executing this on other. 另一个问题-在第一个Creature上执行方法run()停止在另一个上执行。
self
is global and not local. self
是全球的,而不是局部的。 Add var
so they do not overwrite each other. 添加var
这样它们就不会彼此覆盖。
self = this;
needs to be 需要是
var self = this;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.