DIV CSS 佈局教程網

JavaScript 中 this 的六種應用場景實例全解
編輯:關於JavaScript     

this 是 JavaScript 裡最容易讓人困惑的關鍵字之一。它的指向會隨呼叫方式而改變,以下用六個實例把常見場景一次講清楚。

場景一:全域函式中的 this 指向 window

若 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 指向實例本身

用 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>

場景三:原型擴充方法可用 this 取得實例

透過 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

無論是直接引用函式,還是實例化函式,其回傳的閉包函式裡 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>

場景五:HTML 事件中的 this 代表元素本身

<div onclick="test(this)" id="div">Click Me</div>
<script type="text/javascript">
function test(obj) { alert(obj); }
</script>

場景六:事件註冊方式影響 this 指向

在 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 指向誰」這個核心,就能應付絕大多數場景。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved