2013-03-07 3 views
0

У меня есть этот блок кода, и это бросает мне следующую ошибку:Проблемы с setInterval в Nodejs

  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(), как Societ.modifyAspects, this.modifyAspects() и 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'); 
     }, 

    } 
} 

ответ

6

Вы должны связать функцию переданную setInterval в правильном контексте:

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

Это будет определять что this в this.tick на самом деле указывает на, если вы не связываете его, он будет запускаться в контексте таймера (обработка setInterval), как вы заметили в ошибке.

+0

Это отлично работало и научило меня чему-то. Спасибо! :) –

Смежные вопросы