[英]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
功能現在作為一個回調函數的一部分,范圍this
在showIt
功能應該是一樣的.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.