Javascript, keeping this reference when passing argument to function

I am inside a function of an object and I need to call an external function and pass a reference to the function as an argument. This last argument to the function uses the keyword multiple times this

, so I need to bind it to my object. I solved it by running:

   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 you have one to avoid this messy thing var $this = this

.

I also want:

   //... (same as before)
   MyObj.prototype.doSomething= function(){
       var $this = this;
       externalFunction(this.someVar, this.internalFunc, this);
   };
   //... (same as before)

      

from

   function externalFunction(arg1, cbfunc, thisref){
       //bla bla things
       cbfunc.call(thisref, blablaData);
   };

      

but I also find it dirty.

I think there is a better way to do this and I can't see it! Thanks in advance!

+3


source to share


2 answers


this

Local variable assignment is precise and general.



Many libraries simplify your second approach by providing a method that returns a wrapper function and sets an execution context eg. $.proxy

in jQuery (or _.bind

underscore .js).

+1


source


There is another option available to you if you are in a fairly recent browser and use Function.bind

.

This allows you to create a function that is bound to a specific area. In other words, it allows you to define what this

will happen within this function. So you can do it this way.

MyObj.prototype.doSomething= function(){
   externalFunction(this.someVar, this.internalFunc.bind(this, data));
};

      



Follow the link above and scroll down the page to view browser support information.

Edit

There is actually another option that is to use one of the many libraries and frameworks that are out there. Anyone who is worth his salt will be bind

, hitch

, proxy

or otherwise available to you. However, this is all done by wrapping native JS approaches, but they often provide useful additions that make this technique even more valuable.

+2


source







All Articles