I need to access this
from my setInterval
handler
prefs: null,
startup : function()
{
// init prefs
...
this.retrieve_rate();
this.intervalID = setInterval(this.retrieve_rate, this.INTERVAL);
},
retrieve_rate : function()
{
var ajax = null;
ajax = new XMLHttpRequest();
ajax.open('GET', 'http://xyz.com', true);
ajax.onload = function()
{
// access prefs here
}
}
How can I access this.prefs in ajax.onload
?
That's not a beauty solution but it's in common usage:
The default behavior of
setInterval
is to bind to the global context. You can call a member function by saving a copy of the current context. Inside retrieve_rate thethis
variable will be correctly bound to the original context. Here is what your code would look like:Bonus tip: For a plain function reference (as opposed to an object reference which has a member function) you can change the context by using JavaScript's
call
orapply
methods.This would be the cleanest solution, since most of the time you actually want to switch the this context for your consecutive method calls:
Also it's easier to grasp the concept of.
The setInterval line should look like this:-
Edit: The same principle applies to the "
onload
". In this case its common for the "outer" code to do little, it just sets up the request an then sends it. In this case the extra overhead an additinal function as in the above code is unnecessary. Your retrieve_rate should look more like this:-With improving browser support the time is now good to use the EcmaScript 6 enhancement, the arrow
=>
method, to preservethis
properly.Using => method preserves the
this
whenretrieve_rate()
is called by the interval. No need for funky self or passingthis
in parametersWith modern browsers the setInterval method allows additional parameters which are passed through to the function specified by func once the timer expires.
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
Hence, a possible solution can be:
A demo: