jquery $.proxy使用

在某些状况下,咱们调用Javascript函数时候,this指针并不必定是咱们所指望的那个。例如:html

 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 });

这时候怎么办呢,一般的一种作法是这样的:jquery

 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函数。框架

jQuery.proxy(),接受一个函数,而后返回一个新函数,而且这个新函数始终保持了特定的上下文(context )语境。函数

有两种语法:this

jQuery.proxy( function, context )
/**function将要改变上下文语境的函数。
** context函数的上下文语境(`this`)会被设置成这个 object 对象。
**/

jQuery.proxy( context, name )
/**context函数的上下文语境会被设置成这个 object 对象。
**name将要改变上下文语境的函数名(这个函数必须是前一个参数 ‘context’ **对象的属性)
**/

上面的例子使用这种方式就能够修改为:spa

$('#myElement').click(function() {

    setTimeout($.proxy(function() {

        $(this).addClass('aNewClass');  

    }, this), 1000);



});