将此函数中的范围更改为使用 jquery 或 vanilla JavaScript 的调用程序


我想

做的示例代码被注释:

 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;
      }
    }
  });

通常使用下划线,我会使用它的_.bind()函数来执行此操作。我正在处理的代码不使用下划线。使用vanilla JS或jQuery执行此操作的最佳方法是什么?

JavaScript本身提供了.bind

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

这是在假设您无法更改doSomething的实现的情况下进行的。如果可以更改它,请参阅 @10100111001 的答案。

但是您不妨使用当前拥有的代码。我认为在这里使用.bind没有很大的好处。


只是为了好玩,一个简单的.bind版本很容易实现,如果你发现自己在一个不支持它的环境中:

function bind(f, thisValue) {
    return function() {
      return f.apply(thisValue, arguments);
    };
}
var boundF = bind(f, myObj);

你也可以做这样的事情,你可以用正确的 this 值call doSomething callbackFn

var myObj = {};
myObj.doSomething = function (obj) {
    obj.callbackFn.call(this, {some_val: "test"});
}
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?
        this.some_val = result.some_val;
      }
    }
  });
console.log(myObj);

with块几乎是:

  function( result ) {
          if ( result && result.retval !== null )
          {
            with(myObj){
                some_val = result.some_val; // Even,no Need "this" 
            }
           
          }
        }
      

甚至,不需要this