在某些狀況下,咱們調用Javascript函數時候,this指針並不必定是咱們所指望的那個。例如:javascript
1 //正常的this使用 2 $('#myElement').click(function() { 3 4 // 這個this是咱們所指望的,當前元素的this. 5 6 $(this).addClass('aNewClass'); 7 8 }); 9 10 11 //並不是所指望的this 12 $('#myElement').click(function() { 13 14 setTimeout(function() { 15 16 // 這個this指向的是settimeout函數內部,而非以前的html元素 17 18 $(this).addClass('aNewClass'); 19 20 }, 1000); 21 22 });
這時候怎麼辦呢,一般的一種作法是這樣的:html
1 $('#myElement').click(function() { 2 var that = this; //設置一個變量,指向這個須要的this 3 4 setTimeout(function() { 5 6 // 這個this指向的是settimeout函數內部,而非以前的html元素 7 8 $(that).addClass('aNewClass'); 9 10 }, 1000); 11 12 });
可是,在使用了jquery框架的狀況下, 有一種更好的方式,就是使用$.proxy函數。java
jQuery.proxy(),接受一個函數,而後返回一個新函數,而且這個新函數始終保持了特定的上下文(context )語境。jquery
有兩種語法:web
jQuery.proxy( function, context ) /**function將要改變上下文語境的函數。 ** context函數的上下文語境(`this`)會被設置成這個 object 對象。 **/ jQuery.proxy( context, name ) /**context函數的上下文語境會被設置成這個 object 對象。 **name將要改變上下文語境的函數名(這個函數必須是前一個參數 ‘context’ **對象的屬性) **/
上面的例子使用這種方式就能夠修改爲:框架
$('#myElement').click(function() { setTimeout($.proxy(function() { $(this).addClass('aNewClass'); }, this), 1000); });
Jquery實現ready()的源碼
1 function bindReady(){ 2 if ( readyBound ) return; 3 readyBound = true; 4 5 // Mozilla, Opera and webkit nightlies currently support this event 6 if ( document.addEventListener ) { 7 // Use the handy event callback 8 document.addEventListener( "DOMContentLoaded", function(){ 9 document.removeEventListener( "DOMContentLoaded", arguments.callee, false ); 10 jQuery.ready(); 11 }, false ); 12 13 // If IE event model is used 14 } else if ( document.attachEvent ) { 15 // ensure firing before onload, 16 // maybe late but safe also for iframes 17 document.attachEvent("onreadystatechange", function(){ 18 if ( document.readyState === "complete" ) { 19 document.detachEvent( "onreadystatechange", arguments.callee ); 20 jQuery.ready(); 21 } 22 }); 23 24 // If IE and not an iframe 25 // continually check to see if the document is ready 26 if ( document.documentElement.doScroll && typeof window.frameElement === "undefined" ) 27 (function(){ 28 if ( jQuery.isReady ) return; 29 30 try { 31 // If IE is used, use the trick by Diego Perini 32 // http://javascript.nwbox.com/IEContentLoaded/ 33 document.documentElement.doScroll("left"); 34 } catch( error ) { 35 setTimeout( arguments.callee, 0 ); 36 return; 37 } 38 39 // and execute any waiting functions 40 jQuery.ready(); 41 })(); 42 } 43 44 // A fallback to window.onload, that will always work 45 jQuery.event.add( window, "load", jQuery.ready ); 46 }
關鍵:IE or Webkit|Moz 內核判斷、DOMContentLoaded事件、onreadystatechange事件、readyState==「complete」函數