2012-11-25 51 views
1

我havethe以下出口对象:Node.js的可变范围

module.exports = { 
    value: 0, 

    startTimer: function() { 
     setInterval(function() { 
      value++; 
     }, 1000); 
    } 
} 

如何访问value从setInterval函数? 在此先感谢。

+2

module.exports.value – numbers1311407

回答

2

您可以指定的完整路径值:

module.exports = { 
    value: 0, 

    startTimer: function() { 
     setInterval(function() { 
      module.exports.value++; 
     }, 1000); 
    } 
} 

或者,如果你绑定的setTimeoutthis的功能,你可以使用this

module.exports = { 
    value: 0, 

    startTimer: function() { 
     setInterval(function() { 
      this.value++; 
     }.bind(this), 1000); 
    } 
} 

这类似于代码如下,您将不时看到:

module.exports = { 
    value: 0, 

    startTimer: function() { 
     var self = this; 
     setInterval(function() { 
      self.value++; 
     }, 1000); 
    } 
}