I have JS code roughly like this:
function myObject()
{
this.a = 13;
this.fetchData = function()
{
alert(this.a);
getData(this.processData);
}
this.processData = function(data)
{
// do stuff with data
alert(this.a);
}
this.fetchData();
}
function getData(callback)
{
// do async request for data and call callback with the result
}
My problem is: The function fetchData has access to my a variable via the this keyword, but the other function processData does not when called by getData. I understand why this happens, but don’t know how to work around it.
How would you approach this problem preferably in OOP style? (The function getData has to be available to multiple classes)
Two options:
1) Have
getDataaccept a context parameter (usually calledcontextorthisArg) and usecallback.apply(context, ...)orcallback.call(context, ...)to call it. So:2) Create a function that, when called, will turn around and call the original callback with
thisset to the correct value. (This is sometimes called “binding”.)For example, using an explicit closure:
Or have a generic
bindfunction to do it (which will also involve a closure, but in a nice controlled context so it’s not closing over stuff you don’t need). See link below for an example of a simplebindfunction.More: You must remember
this