寫 addEventListener 與 attachEvent 差異的文章不少,但多數把重點放在「前者是 Firefox/Chrome 用的,後者只存在於 IE」這件事上。最近實作事件代理時遇到一個 bug,才發現還有另一個關鍵差異:兩者綁定的處理函式中,this 指向的物件不一樣。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>測試</title>
</head>
<body>
<div id="div1"><a href="#" id="a1">test1</a></div>
<div id="div2"><a href="#" id="a2">test2</a></div>
</body>
<script type="text/javascript">
var testGolb = "diff"; // 定義一個全域變數
var a1 = document.getElementById("a1");
var a2 = document.getElementById("a2");
function getEleId(e) {
alert(this.id); // 第一次 alert
alert(this.testGolb); // 第二次 alert
}
a1.onclick = getEleId; // 用 DOM0 寫法
if (a2.attachEvent) {
a2.attachEvent("onclick", getEleId); // IE 專屬
} else {
a2.addEventListener('click', getEleId); // 標準寫法
}
</script>
</html>
在 Chrome、Firefox、IE 中的結果一致:第一次 alert 顯示 "a1",第二次顯示 "undefined"。
這很好理解:此時 this 指向 #a1 這個 DOM 元素,所以 this.id 是 "a1";而這個元素上並沒有 testGolb 屬性(它是全域變數,挂在 window 上),所以是 undefined。
在 Chrome 與 Firefox 下,結果與 test1 相同:"a1" 這邊顯示的是元素 id,第二次是 undefined。
但在 IE 中完全不同:第一次 alert 顯示 "undefined",第二次顯示 "diff"。
原因就在於:使用 attachEvent 綁定事件時,處理函式中的 this 指向的是 window,而不是綁定事件的那個 DOM 元素。所以 this.id 是 window 的 id(undefined),而 this.testGolb 就是全域變數 testGolb 的值 "diff"。
標準的 addEventListener 則與 DOM0 寫法一致,this 就是當前觸發事件的元素(currentTarget)。
attachEvent 是 IE 在正式標準制訂之前自行實作的機制,它並未遵循後來 DOM Level 2 Events 規範中「處理器內的 this 為 currentTarget」的約定,而是把函式當成普通回呼直接從全域環境呼叫,因此 this 落在 window 上。這是歷史遺留的實作差異,不是 bug。
這個差異在寫事件代理時特別容易出事。事件代理的典型寫法是:
document.getElementById('list').addEventListener('click', function (e) {
var target = e.target;
// 靠 this 取得容器,靠 e.target 取得實際被點的元素
});
如果這段程式在 IE 下改用 attachEvent,this 就不再是容器,凡是依賴 this 的邏輯都會出錯。
不要依賴 this,改用 event.currentTarget。它在標準事件模型中必定指向「目前處理器所綁定的元素」,且 attachEvent 也會傳入 event 物件:
function handler(e) {
e = e || window.event; // IE 用 window.event
var current = e.currentTarget; // 標準:綁定的元素
if (!current) {
current = this; // 舊 IE 的後退方案
}
var target = e.target || e.srcElement; // 實際被點擊的元素
// ...
}
或者更根本的解法:統一用事件註冊的封裝函式,讓差異只存在一處:
function addEvent(el, type, handler) {
if (el.addEventListener) {
el.addEventListener(type, handler, false);
} else if (el.attachEvent) {
// 用闭包把 el 帶進去,補回 this 的正確指向
el.attachEvent('on' + type, function (e) {
handler.call(el, e || window.event);
});
} else {
el['on' + type] = handler;
}
}
handler.call(el, ...) 這一行是關鍵——用 call 明確指定 this,把 attachEvent 造成的偏差補回來。
IE6–8 已完全退出支援,attachEvent 在現代開發中不再需要考慮。但這個案例的價值在於提醒一件更普遍的事:不要假設「同一個 API 名稱在不同實作下的行為一致」。this 的指向、事件的觸發順序、捕獲與冒泡的支援程度,這些細節在歷史上的差異遠比想像中多。寫跨瀏覽器程式碼時,優先依賴標準 API 並用 feature detection 而非 browser sniffing,才能避開這類隱藏的坑。