I’m inside a function of an object and I need to call an external function and pass a reference to a function as argument. This last function argument uses the keyword this several times so I need to be scoped into my object. I solved this by doing:
MyObj.prototype.internalFunc= function(data){
this.doSomethingWithReturnedData(data);
};
MyObj.prototype.doSomething= function(){
var $this = this;
externalFunction(this.someVar, function(data){ $this.internalFunc(data); });
};
var objInst = new MyObj();
objInst.doSomething();
I want to know if there is away to avoid this messy var $this = this thing.
I also thoung of:
//... (same as before)
MyObj.prototype.doSomething= function(){
var $this = this;
externalFunction(this.someVar, this.internalFunc, this);
};
//... (same as before)
with
function externalFunction(arg1, cbfunc, thisref){
//bla bla things
cbfunc.call(thisref, blablaData);
};
but I also find it messy.
I think there is a better way of doing it and I’m not seeing it! Thanks in advance!
Assigning
thisto a local variable is fine and common.Many libraries make your second approach easier by providing a method that returns a wrapper function and sets the execution context, e.g.
$.proxyin jQuery (or_.bindin underscore.js).