0

我有这段代码,它向我抛出了以下错误:

            this.modifyAspect('health');
                 ^
TypeError: Object #<Timer> has no method 'modifyAspect'
    at Timer.tick (/Users/martinluz/Documents/Nodes/societ/node_modules/societal/societal.js:93:9)
    at Timer.exports.setInterval.timer.ontimeout (timers.js:234:14)

我试过调用modifyAspects()as Societ.modifyAspects, this.modifyAspects()and modifyAspects(), 只得到错误。任何帮助或建议表示赞赏...

这是代码:

  var Societ = function(inboundConfig){

    this.population = undefined;
    this.owner_id =  undefined;
    this.owner_name = undefined;
    this.config = inboundConfig;
    this.aspects = {
        education:{
            facilities: undefined,
            rating: undefined
        },
        health: {
            facilities: undefined,
            rating: undefined
        }
    };

    this.modifiers = {
        health: 1,
        education: 2,
        population: 2
    };

    this.tickio = function(){
        console.log('tickio');
    }

    return{
        config: this.config,
        bootstrap: function(){
            this.owner_id = this.config.owner_id;
            setInterval(this.tick, 10000); /*** Problematic line ***/
        },
        yield: function(){

            console.log(this.population);   
        },
        getOwnerId: function(){
            return this.owner_id;
        },
        modifyAspect: function(aspect){
            console.log('Modifying aspect: '+aspect);
        },
        tick: function(){
            console.log('Ticking!');
            this.modifyAspect('health');
            console.log('Recalculate education');
            console.log('Recalculate population');
        },

    }
}
4

1 回答 1

6

您需要将传递给的函数绑定setInterval到正确的上下文:

setInterval(this.tick.bind(this), 10000);

这将定义thisinthis.tick实际指向的内容,如果您不绑定它,它将在计时器(处理setInterval)的上下文中运行,正如您在错误中注意到的那样。

于 2013-03-07T17:56:26.740 回答