node.js variable scopes
Problem
I havethe following exported object:
module.exports = {
value: 0,
startTimer: function() {
setInterval(function() {
value++;
}, 1000);
}
}
How can I access value
from that setInterval function?
Thanks in advance.
Problem courtesy of: john smith
Solution
You can either specify the full path to the value:
module.exports = {
value: 0,
startTimer: function() {
setInterval(function() {
module.exports.value++;
}, 1000);
}
}
Or, if you bind the function called by setTimeout
to this
, you can use this
:
module.exports = {
value: 0,
startTimer: function() {
setInterval(function() {
this.value++;
}.bind(this), 1000);
}
}
This is similar to code like this, which you will see from time to time:
module.exports = {
value: 0,
startTimer: function() {
var self = this;
setInterval(function() {
self.value++;
}, 1000);
}
}
Solution courtesy of: Michelle Tilley
Discussion
View additional discussion.