JQuery this 和 $(this) 詳解
this
this 在麵向對象語言中,指代調用上下文對象,在js中,也是一模一樣的概念,所以不管這個this出現在什麼地方,隻要追蹤到當前調用對象是什麼,那麼this是什麼也就一目了然了。
先看一個簡單示例
(function(){ console.log("Normal function being invoked by: "+ this); })();
輸出: Normal function being invoked by: [object Window]
這是個普通匿名函數,當運行這段代碼,誰是宿主對象呢,對, 全局變量window, 所以這裏的this 就是 window不過請注意如果是在嚴格模式下,這裏的this是undefined, 下麵代碼可以驗證
(function(){ 'use strict'; console.log("Normal function in strict: "+ this); })();
輸出:Normal function in strict: undefined
上麵的用法很傻,更常用的方式是在自定義的對象中用this指代自身,例如
var o = { name: "Frank", sayName : function (){console.log(this.name)}} o.sayName();輸出:Frank
還有一個更實用的用法,是在函數中指代一個“未知的”調用上下文,也就是在定義函數時用到了this,但是這個函數被誰調用,我還不清楚,請在運行時自行綁定,這種用法在回調(callback)中很普遍,而實現這種函數和對象的動態關聯,是通過函數的call( )和 apply( ) 方法實現的,看例子
var o = { name: "Frank", age: 21} function sayAge(){ console.log("My age is "+this.age)// 這個this 表示哪個對象調用我,我就是誰 } sayAge.call(o); //當前上下文是 o, 所以age是21 sayAge(); //當前上下文是 Window, Window沒有age這個屬性,所以是undefined
輸出:
My age is 21
My age is undefined
OK, 理解了this,那麼$(this) 就很簡單了,在jQuery中,其作用就是將DOM對象wrap成一個jQuery對象,看個例子
<script src="jQuery.js" type="text/javascript"></script> <script> $(function() { $('div').each(function(){ this.style.color = "blue"; // this here is DOM element, because this function is fired by in the context of the current DOM element $(this).css( "color", "red" ); // use $(this) to wrap it to be jQuery object }); }); </script> <html> <body> <div> Sample 1 </div> <div> Sample 2 </div> </body> </html>
此例中,each的參數是一個匿名的callback函數,其中的this就是前麵介紹過的用法,指代運行時的調用對象,詳細參見: https://api.jquery.com/each/
jQuery是怎麼做到的呢? 看一下源碼,很簡單的
each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { // 就是這裏了,通過call將執行callback函數的上下文設置為obj[i], 因為this指代函數運行時,invoke函數的對象(上下文),所以此時的this也就是obj[i]。而obj[i] 就是jQuery對象(數組)中的DOM對象,第二個參數是index,第三個參數基本不用,因為就是this value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { // 如果你想終止loop,隻要在回調函數中返回false就可以了 break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; },
最後更新:2017-04-03 12:54:47