繁体   English   中英

使用jquery或vanilla javascript将此函数的范围更改为调用者

[英]change the scope in this function to the invoker with jquery or 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);

你也可以这样做,你可以使用正确的值call doSomethingcallbackFn

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM