網路上談 jQuery 中 this 與 $(this) 的文章很多,多數只釐清了兩者的指向,卻很少說明它們各自適用在哪裡。其實不能一概而論地說「在 jQuery 呼叫成員函數時 this 就是 DOM 物件」。
$(this) 指向 jQuery 物件是理所當然的;而 this 指向 DOM 物件,則是因為 jQuery 做了特別處理。
建立 DOM 的 jQuery 物件時,jQuery 不只包裝它,還把 DOM 存進所建立物件的陣列中:
elem = document.getElementById(match[2]);
if (elem && elem.parentNode) {
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
this[0] = elem 這一行就是關鍵。所以 JavaScript 其實很有意思:this 既可以當成物件來存取成員,同時本身又是一個存放 DOM 物件的陣列。
$("p").each() 的原始碼:
each: function( callback, args ){
return jQuery.each( this, callback, args );
}
傳進 jQuery.each 的是這個「物件陣列」,而陣列裡存的是 DOM 物件,因此在 callback 當中的 this 自然就是 DOM 物件了。
$("p").hide() 的原始碼:
hide: function(){
return showHide( this );
}
function showHide( elements, show ){
var elem, display, values = [], index = 0, length = elements.length;
for ( ; index < length; index++ ){
elem = elements[ index ];
if ( !elem.style ) { continue; }
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
for ( index = 0; index < length; index++ ){
elem = elements[ index ];
if ( !elem.style ) { continue; }
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
可見 hide() 實際呼叫的是 showHide,傳入的第一個參數 this 並不是 DOM 物件,而是 jQuery 的物件陣列;showHide 再透過迴圈取出其中每一個 DOM 元素來處理。第二個迴圈刻意分開,是為了避免在同一輪中反覆觸發 reflow。
$("p").bind() 的原始碼:
bind: function( types, data, fn ){
return this.on( types, null, data, fn );
}
on: function( types, selector, data, fn, one ){
// 中間邏輯略
return this.each( function(){
jQuery.event.add( this, types, fn, data, selector );
});
}
bind 呼叫 on,on 又透過 each 完成 jQuery.event.add。此時傳進 jQuery.event.add 的 this,正是 each 迭代中的當前 DOM 元素 —— 所以事件處理函數裡的 this 也就是 DOM 物件。
小結:this 指向誰,取決於 jQuery 內部怎麼呼叫它。each 系列(含事件綁定)迭代到元素層級,this 是 DOM 物件;而 hide/show 這類成員函數把整個 jQuery 物件陣列往內部傳,此時的 this 是 jQuery 物件。理解這一點,就能判斷任何時候該寫 this.id 還是 $(this).attr("id")。