[英]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.