randombits randombits - 3 months ago 34
Javascript Question

change the scope in this function to the invoker with jquery or vanilla javascript

Sample code with what I want to do is commented:

myObj.doSomething({
callbackFn: function( result ) {
if ( result && result.retval !== null )
{
// I want to assign the values on result.retval to myObj
// but `this` is not equal to myObj.
// is it correct to just do this?
myObj.some_val = result.some_val;
}
}
});


Normally with underscore, I'd use its
_.bind()
function to do this. The code I'm dealing with doesn't use underscore. What's the best way to do this with vanilla JS or jQuery?

Answer

JavaScript itself provides .bind:

myObj.doSomething({
    callbackFn: function( result ) {
      if ( result && result.retval !== null )
      {
        this.some_val = result.some_val;
      }
    }.bind(myObj); // <--
  });

This is under the assumption that you cannot change the implementation of doSomething. If you can change it, see @10100111001's answer.

But you might as well use the code you currently have. I don't see a big benefit of using .bind here.


Just for fun, a simple version of.bind is pretty easy to implement yourself, should you find yourself in an environment that doesn't support it:

function bind(f, thisValue) {
    return function() {
      return f.apply(thisValue, arguments);
    };
}

var boundF = bind(f, myObj);