[英]Why does `this` change when passing the function argument as string or reference?
看看這個:
var a = {
b: function() {
console.log(this);
}
}
// Example 1
a.b(); // a
// Example 2
eval('a.b()'); // a
// Example 3
setTimeout('a.b()', 100); // a
// Example 4
setTimeout(a.b, 100); // Window
// Example 5
var c = a.b;
c(); // Window
假設預期的結果是我所期望的......
當調用b()
時, Object
的屬性, this
成為屬性的Object
,這里是父級a
。 它產生了預期的結果。
eval()
旨在采用其調用位置的執行上下文,在本例中為window
。 它也產生了預期的結果。
將字符串傳遞給setTimeout()
時,我想它會通過與eval()
非常相似的東西運行。 它也產生了預期的結果。
在本例中, this
變為Window
。 這是我感興趣的。
這里this
變成Window
,因為c
的父 object 是Window
。
當僅傳遞對 function (例如ab
)的引用時,當使用()
調用時,它的this
是否總是Window
?
將this
a
字符串傳遞給setTimeout()
/ setInterval()
的唯一方法是嗎?
當僅傳遞對 function (egab) 的引用時,當使用 () 調用時,它是否總是 Window?
是的
將其作為字符串傳遞給 setTimeout() / setInterval() 的唯一方法是嗎?
否。改為創建一個新的 function。
setTimeout(function() { a.b() }, 100);
開發人員經常對 javascript 的this關鍵字感到困惑。 要記住的最重要的事情是它是由調用提供的。
在第四個例子中:
// Example 4 setTimeout(ab, 100); // Window
第一個參數是對 function 的引用,因此在沒有任何“父”object 的情況下調用它。 由於調用不提供 object,因此將其設置為window
。
您對示例 5 的評論:
這里 this 變成 Window,因為 c 的父 object 是 Window。
並不是真的不正確。 Because the function call doesn't provide an object to use as this
, it is set to window
(which is the default when no object is provided).
將其作為字符串傳遞給 setTimeout() / setInterval() 的唯一方法是嗎?
不。除了將其稱為 object 的屬性外,您可以使用call
或apply
:
var x = a.b;
x.call(a);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.