在使用jquery操作js時,經(jīng)常弄不明白this與$(this)。最近不是很忙,抽空仔細(xì)研究了一下,記錄下來以供在忘記的時候拉出來參考參考!
網(wǎng)上有很多關(guān)于jQuery的this和$(this)的介紹,大多數(shù)只是理清了this和$(this)的指向,其實它是有應(yīng)用場所的,不能一概而論在jQuery調(diào)用成員函數(shù)時,this就是指向dom對象。
$(this)指向jQuery對象是無可厚非的,但this就是指向dom對象,這個是因為jQuery做了特殊的處理。
在創(chuàng)建dom的jQuery對象時,jQuery不僅僅為dom創(chuàng)建一個jQuery對象,而且還將dom存儲在所創(chuàng)建對象的數(shù)組中。
復(fù)制代碼代碼如下:
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這條語句就是實現(xiàn)對象數(shù)組。所以javascript是很有意思的語言,使用this訪問時,可以訪問它所指向的對象的成員函數(shù),而其實this又是一個對象數(shù)組。其存放的是dom對象。
先看看 $("p").each() -- 循環(huán)
復(fù)制代碼代碼如下:
each: function( callback, args ) {
return jQuery.each( this, callback, args );
}
看了each函數(shù)的調(diào)用大家應(yīng)該明白,jQuery.each( this, callback, args );調(diào)用的是對象數(shù)組,而對象的數(shù)組存儲的是dom對象,因此在callback函數(shù)中的this自然是dom對象了
再看看$("p").hide() -- 成員函數(shù)
復(fù)制代碼代碼如下:
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 ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
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 );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
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行數(shù)其實調(diào)用的是showHide,而傳入的第一個參數(shù)this,并不是dom對象,而是jQuery對象數(shù)組,因此showHide函數(shù)通過循環(huán)此對象數(shù)組獲取每一個dom對象。
最后看看$("p").bind() -- 事件
復(fù)制代碼代碼如下:
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
復(fù)制代碼代碼如下:
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
// 此部分代碼省略
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
bind函數(shù)調(diào)用的是 on函數(shù),而on函數(shù)又是通過 each函數(shù)實現(xiàn)了jQuery.event.add。因此 jQuery.event.add( this中的this也就是dom對象了。所以事件中的this也就是dom對象了。
以上就是個人對于jQuery中this與$(this)的理解了,如有什么紕漏,請聯(lián)系我或者給我留言