撰寫 jQuery 外掛($.fn.extend)時,this 指向的是 jQuery 實例物件(類陣列),而非原生 DOM 元素。這是初學者最常混淆的點,導致 this.nodeName 為 undefined、this == document.body 為 false。
$.fn.extend({
im: function() {
console.log($(this).attr('id')); // 正確:包裝後可用 jQuery 方法
console.log(this == document.body); // false:this 是 jQuery 物件
console.log(this.nodeName); // undefined:jQuery 物件無 nodeName
}
});
$('body').im();
| 情境 | this 指向 | 取得 DOM 元素 | 取得 jQuery 物件 |
|---|---|---|---|
外掛函式 $.fn.xxx = function() | jQuery 實例(類陣列) | this[0] 或 this.get(0) | this (已是 jQuery 物件) |
事件處理器 $('.btn').click(function()) | 原生 DOM 元素 | this | $(this) |
迴圈回呼 .each(function()) | 原生 DOM 元素 | this | $(this) |
$.fn.extend({
im: function() {
// 方式 1:取第一個 DOM 元素
var dom = this[0];
console.log(dom == document.body); // true
console.log(dom.nodeName); // "BODY"
// 方式 2:用 jQuery 方法(自動處理集合)
console.log(this.attr('id')); // 直接用 this,因為外掛 this 已是 jQuery 物件
// 或
console.log($(this[0]).attr('id'));
}
});
this.each(function() { var dom = this; ... }),回呼中 this 為 DOM 元素。return this; 以支援鏈式呼叫。myPlugin_doSomething)。搞懂 jQuery 不同情境下的 this 指向,是編寫健壯外掛與避免「undefined 不是函式」錯誤的關鍵。