jquery $.proxy使用
在某些情况下,我们调用Javascript函数时候,this指针并不一定是我们所期望的那个。例如:
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 });这时候怎么办呢,通常的一种做法是这样的:
1 $('#myElement').click(function() {2 var that = this; //设置一个变量,指向这个需要的this3 4 setTimeout(function() {5 6 // 这个this指向的是settimeout函数内部,而非之前的html元素7 8 $(that).addClass('aNewClass');9
10 }, 1000);
11
12 });但是,在使用了jquery框架的情况下, 有一种更好的方式,就是使用$.proxy函数。
jQuery.proxy(),接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文(context )语境。
有两种语法:
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”




















