簡體   English   中英

jquery的回調函數中的范圍

[英]the scope of this in jquery's callback function

我的jquery活動如下:

$('body').on('click', '.show-it', function (e) {
       e.preventDefault();
       showIt();
});

function showIt() {...};

showIt函數中,當我想嘗試訪問$(this) ,它總是返回window對象。 據我所知,因為showIt功能現在作為一個回調函數的一部分,范圍thisshowIt功能應該是一樣的.show-it按鈕的點擊回調函數,這是一個點擊的元素。 但似乎不是。 我必須使用self.showIt.call(this)()在回調函數來獲得的權利范圍this 那么現場背后發生了什么?

JQuery使用callback.call(el)或等效表達式將this的值設置為回調函數中的給定DOM元素。 但是這並沒有級聯到該回調中調用的其他函數。 試試看:

var o = {
    name: "baz",
    foo: function() {
        console.log(this);
    }
}

function foo() {
    console.log(this);
}

function bar() {
    console.log(this); // bar's this
    foo();             // the global object
    foo.call(this);    // bar's this
    o.foo();           // o
    o.foo.call(this);  // bar's this
}

bar.call(new Date());

輸出:

Thu Feb 13 2014 13:26:47 GMT-0800 (PST)
Window {top: Window, window: Window, location: Location...}
Thu Feb 13 2014 13:26:47 GMT-0800 (PST) VM350:10
Object {name: "baz", foo: function}
Thu Feb 13 2014 13:26:47 GMT-0800 (PST)

需要注意的是,當你調用一個函數是一個對象的屬性, this被綁定到該對象,不管this是在調用上下文,除非該功能以前使用綁定Function.bind

暫無
暫無

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

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