this 是 JavaScript 裡最容易讓人困惑的關鍵字之一。它的指向會隨呼叫方式而改變,以下用六個實例把常見場景一次講清楚。
若 function 是全域函式,則 this 等同 window 物件。函式內定義的屬性或方法,只要在函式被呼叫後,就能從外部存取。
<script type="text/javascript">
function a() {
if (this == window) {
alert("this == window");
this.fieldA = "I'm a field";
this.methodA = function() { alert("I'm a function "); }
}
}
a(); // 不呼叫 a,裡面定義的屬性就取不到
alert(window.fieldA);
methodA();
</script>
用 new 建立物件時,this 不再等於 window,而是指向函式 a 的實例。
<script type="text/javascript">
function a() {
if (this == window) { alert("this == window"); }
else { alert("this != window"); }
this.fieldA = "I'm a field";
}
var b = new a();
alert(b.fieldA);
</script>
透過 prototype 擴充的方法能用 this 取得源物件的實例,但私有欄位無法經由原型鏈取得。
<script type="text/javascript">
function a() {
this.fieldA = "I'm a field";
var privateFieldA = "I'm a var";
}
a.prototype.ExtendMethod = function(str) {
alert(str + " : " + this.fieldA);
alert(privateFieldA); // 出錯
};
var b = new a();
b.ExtendMethod("From prototype");
</script>
無論是直接引用函式,還是實例化函式,其回傳的閉包函式裡 this 都指向 window。
<script type="text/javascript">
function a() {
alert(this == window);
var that = this;
var func = function() {
alert(this == window);
alert(that);
};
return func;
}
var b = a(); b();
var c = new a(); c();
</script>
<div onclick="test(this)" id="div">Click Me</div>
<script type="text/javascript">
function test(obj) { alert(obj); }
</script>
在 IE 與 Firefox(Chrome)下註冊事件時,this 的分別指向 window 與元素本身,這點在跨瀏覽器開發時特別需要留意。
<div id="div">Click Me</div>
<script type="text/javascript">
var div = document.getElementById("div");
if (div.attachEvent) {
div.attachEvent("onclick", function() {
alert(this == window);
var e = event;
alert(e.srcElement == this);
});
}
if (div.addEventListener) {
div.addEventListener("click", function(e) {
alert(this == window);
e = e;
alert(e.target == this);
}, false);
}
</script>
以上便是 this 在 JavaScript 中幾種典型的應用情境。它的指向規則看似繁瑣,但只要掌握「怎麼呼叫,取決於 this 指向誰」這個核心,就能應付絕大多數場景。