修改Meteor.setInterval函数中的类属性

时间:2015-01-27 00:11:58

标签: javascript meteor setinterval

我需要这样做:

TestClass = function(){
   this.left =10
   this.finterval = function(){
       console.log("this.finterval:"+JSON.stringify(intervalId))
       this.left =  this.left -1
       Meteor.clearInterval(intervalId)
   }
   var intervalId = Meteor.setInterval(this.finterval,1000)
   console.log("this.intervalId:" + this.intervalId)
}

有没有办法在区间方法中修改this.left?

1 个答案:

答案 0 :(得分:1)

this始终引用当前范围,因此如果您要嵌套函数,则需要将其分配给另一个var(ex self):

TestClass = function(){
   this.left =10
   var self = this;
   this.finterval = function(){
       console.log("this.finterval:"+JSON.stringify(intervalId))
       self.left =  self.left -1
       Meteor.clearInterval(intervalId)
   }
   var intervalId = Meteor.setInterval(this.finterval,1000)
   console.log("this.intervalId:" + this.intervalId)
}