$.proxy() 最主要就是用来修改函数执行时的上下文对象的。
先看以下情景:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<div id= "panel" style= "display:none;" > <button class = "close" >消失</button> </div> <script> $( "#panel" ).fadeIn( function () { $( '.close' ).click( function () { $( this ).fadeOut(); // 其实这里我想让 #panel 隐藏来着 }); }); $( '#panel' ).click( function () { setTimeout( function () { $( this ).addClass( 'aNewClass' ); // 这个 this 根本就不对嘛 }, 1000); }); </script> |
打断一下...这里用 var $this = $(this); 来处理也可以呀。
妈蛋,还让不让我讲了啊喂。骚年郎,你是还没接触到 this 这门艺术的高深之处才会这样觉得,将 this 不去标量化才是我们装逼的价值。
不但少了个生成变量的性能输出,还避免了变量名耦合,最极致的莫过于提高了复用性...
看一眼改版后的代码
1 2 3 4 5 6 7 8 9 10 11 12 |
$( "#panel" ).fadeIn( function (){ $( '.close' ).click($.proxy(HidePanel, this )); // 相比这个 $('.close').click(function(){HidePanel()}); 优美很多 }); function HidePanel() { $( this ).fadeOut(); } $( '#panel' ).click( function () { setTimeout($.proxy( function () { $( this ).addClass( 'aNewClass' ); }, this ), 1000); }); |
上文说的是 $.proxy(fn, context) 用法,
而 $.proxy(context, name) 用法感觉更多的用在对象上,个人用的较少,因为感觉 new 一个对象函数要更爽(而 new 出来的 this 肯定不会乱了呀),不过还是列一下吧
1 2 3 4 5 6 |
var person = { name: "zyh" , say: function (event) {alert( this .name)}, } // $('#test').click(person.say) 显然有问题 $( '.test' ).click($.proxy(person, 'say' )); |