本文共 1537 字,大约阅读时间需要 5 分钟。
jQuery.proxy(),接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文(context
·
function将要改变上下文语境的函数。
context函数的上下文语境(`this`)会被设置成这个 object 对象。
·
context函数的上下文语境会被设置成这个 object 对象。
name将要改变上下文语境的函数名(这个函数必须是前一个参数 ‘context’ 对象的属性)
这个方法通常在向一个元素上附加事件处理函数时,上下文语境实际是指向另一个对象的情况下使用。
另外,jQuery 能够确保即使你绑定的函数是经过 jQuery.proxy() 处理过的函数,你依然可以用原先的函数来正确地取消绑定。
看一下官方的例子:
01 | var | |
02 | name: |
03 | test: | |
04 | alert( |
05 | $("#test").unbind("click", obj.test); | |
06 | } |
07 | }; |
08 | |
09 | $("#test").click( jQuery.proxy( obj, | |
10 | |
11 | // 以下代码跟上面那句是等价的: | |
12 | // $("#test").click( jQuery.proxy( obj.test, obj ) ); |
13 | | |
14 | // 可以与单独执行下面这句做个比较。 |
15 | // $("#test").click( obj.test ); |
再看一下jquery.proxy的源码:
01 | | |
04 | jQuery.proxy = |
05 | | |
06 | |
07 | | |
08 | |
09 | | |
10 | |
11 | | |
12 | |
17 | | |
18 | |
19 | | |
20 | |
21 | | |
22 | |
23 | | |
24 | |
25 | | |
26 | |
27 | | |
28 | |
29 | | |
30 | |
31 | | |
32 | |
33 | | |
34 | |
35 | | |
36 | } |
其实就是平常使用的的call和apply,大部分的时候作为回调使用。
转载地址:http://pvqdi.baihongyu.com/