JavaScript 有一套自己的 this 機制,在不同情況下,this 的指向也不盡相同。
console.log(this); // 全域物件
在全域範圍使用 this,指向的是全域物件,瀏覽器環境下就是 window。注意:ECMAScript 5 的 strict 模式下不存在全域物件,這裡的 this 是 undefined。
function foo() {
console.log(this);
}
foo(); // 全域物件
函式呼叫中的 this 也指向全域物件。同樣地,在 strict 模式下,這裡的 this 是 undefined。
var test = {
foo: function () {
console.log(this);
}
}
test.foo(); // test 物件
物件方法呼叫中,this 指向呼叫者。
var test = {
foo: function () {
console.log(this);
}
}
var test2 = test.foo;
test2(); // 全域物件
由於 this 具有「晚綁定」特性,上例中 this 將指向全域物件,相當於直接呼叫函式。這一點非常重要:同樣的程式碼段,只有在執行時才能確定 this 的指向。
function Foo() {
console.log(this);
}
new Foo(); // 新建立的物件
在構造函式內部,this 指向新建立的物件。
function foo(a, b) {
console.log(this);
}
var bar = {};
foo.apply(bar, [1, 2]); // bar
foo.call(bar, 1, 2); // bar
使用 Function.prototype 的 call 或 apply 方法時,函式內部的 this 會被設定為傳入的第一個參數。