Reputation:
I have code that looks like this:
var X = {
updateAll: function() {
// ...
},
init: function() {
window.setInterval(function() {
this.updateAll();
}, 40000);
}
}
In X.init()
, I want to be able to access updateAll()
, but for obvious reasons it does not work as intended.
How can I achieve the required outcome?
Upvotes: 0
Views: 332
Reputation: 3038
You can use the var self = this
method as mentioned in other answers, OR you can use the .bind method that functions have:
var X = {
updateAll: function() {
// ...
},
init: function() {
window.setInterval(
this.updateAll.bind(this),
40000
);
}
}
Please note that you don't need all that "function() {...}" in the first argument to setInterval -- it's redundant.
Upvotes: 0
Reputation: 1875
You can bind the function:
init: function() {
window.setInterval(function() {
this.updateAll();
}.bind(this), 40000);
}
Or, if you are using ECMAScript 2015, you can use an arrow function:
init: function() {
window.setInterval(() => {
this.updateAll();
}, 40000);
}
Upvotes: 0
Reputation: 2523
you can do it this way.
var X = {
updateAll: function() {
console.log('updateALL');
},
init: function() {
var self=this;
window.setTimeout(function() {
self.updateAll();
}, 200);
}
};
Upvotes: 0
Reputation: 2642
init: function() {
var _self = this;
window.setInterval(function() {
_self.updateAll();
}, 40000);
}
Upvotes: 3