jquery中的proxy函数

stackoverflow上一个关于jquery的Porxy函数的解答。
原地址:http://stackoverflow.com/questions/4986329/understanding-proxy-in-jquery

What it ultimately does is it ensures that the value of this in a function will be the value you desire.

A common example is in a setTimeout that takes place inside a click handler.

Take this:

$('#myElement').click(function() {
        // In this function, "this" is our DOM element.
    $(this).addClass('aNewClass');
});

The intention is simple enough. When myElement is clicked, it should get the class aNewClass. Inside the handler this represents the element that was clicked.

But what if we wanted a short delay before adding the class? We might use a setTimeout to accomplish it, but the trouble is that whatever function we give to setTimeout, the value of thisinside that function will be window instead of our element.

$('#myElement').click(function() {
    setTimeout(function() {
          // Problem! In this function "this" is not our element!
        $(this).addClass('aNewClass');
    }, 1000);
});

So what we can do instead, is to call $.proxy(), sending it the function and the value we want to assign to this, and it will return a function that will retain that value.

$('#myElement').click(function() {
   // ------------------v--------give $.proxy our function,
    setTimeout($.proxy(function() {
        $(this).addClass('aNewClass');  // Now "this" is again our element
    }, this), 1000);
   // ---^--------------and tell it that we want our DOM element to be the
   //                      value of "this" in the function
});

So after we gave $.proxy() the function, and the value we want for this, it returned a function that will ensure that this is properly set.

How does it do it? It just returns an anonymous function that calls our function using the .apply()method, which lets it explicitly set the value of this.

A simplified look at the function that is returned may look like:

function() {
    // v--------func is the function we gave to $.proxy
    func.apply( ctx );
    // ----------^------ ctx is the value we wanted for "this" (our DOM element)
}

So this anonymous function is given to setTimeout, and all it does is execute our original function with the proper this context.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值