[英]node.js variable scopes
我有以下导出的对象:
module.exports = {
value: 0,
startTimer: function() {
setInterval(function() {
value++;
}, 1000);
}
}
如何从该 setInterval 函数访问value
? 提前致谢。
您可以指定值的完整路径:
module.exports = {
value: 0,
startTimer: function() {
setInterval(function() {
module.exports.value++;
}, 1000);
}
}
或者,如果将setTimeout
调用的函数绑定到this
,则可以使用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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.