簡體   English   中英

如果從存儲的變量調用jquery函數,則綁定錯誤

[英]this is bound incorrectly if jquery function is called from a stored variable

我以兩種方式調用jQuery函數,一種有效,另一種無效,因為this綁定不正確。

$('#my-div').fadeOut();

可以按預期工作, fadeOut函數內部的this值是jQuery對象。

var fadeOutFn = $('#my-div').fadeOut;
fadeOutFn();

不起作用,因為價值this是現在Window

這是兩個示例的jsfiddle。

http://jsfiddle.net/XCAdP/

編輯:添加一些關於為什么我發布問題的說明,我真的不想知道如何解決這個問題。 那不是問題。 我想了解為什么會這樣。

是的,它不知道要向其應用fadeOut動畫的元素,在這種情況下, this上下文主要是窗口,而不是jquery對象。 您可以使用function.call傳遞上下文

嘗試這個:

var fadeOutFn = $('#my-div').fadeOut;
fadeOutFn.call($('#my-div'));

或者只是這樣做:

使用function.bind將上下文綁定到函數引用,然后調用它。

var fadeOutFn = $().fadeOut.bind($('#my-div'));
fadeOutFn();

讀取function.bind

對於不受支持的瀏覽器,您可以按照文檔中的說明將此內容添加到js文件中以獲取支持:

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

是的,當獲取方法作為函數引用時,可以將其與對象斷開連接。 僅當在對象的上下文中調用函數時,該函數才用作方法,通常使用來完成. 運算符,例如obj.method()

如果在沒有對象上下文的情況下調用函數,則將全局范圍作為上下文(即window對象)進行調用。 例:

var obj = {
  name: "obj",
  method: function() { alert(this.name); }
};

obj.method(); // shows the name "obj"
var m = obj.method;
m(); // shows the name of window
m.call(obj); // shows the name "obj"

var obj2 = {
  name: "obj2"
};
m.call(obj2); // shows the name "obj2" (using the method from obj)

如果要使其用作方法,則必須以對象作為上下文來調用它:

var obj = $('#my-div');
var fadeOutFn = obj.fadeOut;
fadeOutFn.call(obj);

您可以使用proxy方法制作一個函數,以正確的上下文調用該函數:

var obj = $('#my-div');
var fadeOutFn = $.proxy(obj.fadeOut, obj);
fadeOutFn();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM