var getById = document.getElementById;
getById("logo"); // TypeError: Illegal invocation
document.getElementById 內部依賴 this 指向 document 物件。直接賦值給變數並呼叫時,this 變為 window(或 strict mode 下的 undefined),導致原生方法拋出 Illegal invocation。
var getById = document.getElementById;
getById.call(document, "logo"); // 正確
const getById = (id) => document.getElementById(id);
getById("logo"); // 正確
function getById(id) {
return document.getElementById(id);
}
getById("logo"); // 正確
document.querySelector / querySelectorAllelement.addEventListener / removeEventListenerconsole.log(部分瀏覽器)Array.prototype.forEach 等陣列方法傳遞回調時原生 DOM 方法多為 this-sensitive,提取出來獨立呼叫必須顯式綁定 this。日常開發建議直接封裝成函數或使用箭頭函數,避免踩坑。