Skip to content Skip to sidebar Skip to footer

Javascript, Preserving This Reference When Passing Function Argument

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

Solution 1:

There is one other option available to you, if you're on a recent enough browser and that is to use Function.bind.

This allows you to create a function that has been bound to a specific scope. Put another way, it allows you to define what this will be, inside that function. Thus, you could do it this way.

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

Follow the link above and scroll to the bottom to see information about browser support.

Edit

Actually, there's one other option, which is to use one of the many libraries and frameworks that are out there. Any one worth its salt will have a bind, hitch, proxy or otherwise available to you. However, all these are doing are wrapping up the native JS approaches, but they often provide useful additions that make this technique even more valuable.

Solution 2:

Assigning this to 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. $.proxy in jQuery (or _.bind in underscore.js).

Post a Comment for "Javascript, Preserving This Reference When Passing Function Argument"