簡體   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