为什么setInterval添加的函数会停止执行?

时间:2015-04-22 13:00:07

标签: javascript underscore.js

我有代码:

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的新变量,并执行其方法run():

var sampleCreature = new Creautre(1);
sampleCreature.run();

在控制台中显示一条消息:

  

1正在运行

每秒重复一次。没关系。

但是如果我添加了具有任何其他名称的新生物 - 控制台中的消息会停止重复,直到我再次在Creature上使用方法run()。

另一个问题 - 在第一个Creature上执行方法run()会停止在另一个上执行此操作。

1 个答案:

答案 0 :(得分:3)

self是全球性的,而不是本地的。添加var,以便它们不会互相覆盖。

self = this;

需要

var self = this;
相关问题