jquery.proxy记录

今天在代码中看到了这么一个方法$.proxy(funciton,context),然后就到jquery官网查询了一下它的用法,记载一下,加深记忆,方便将来使用查询。

下面是jquery官网的介绍:

jquery1.4版本增加的两个函数:

1)

jQuery.proxy( function, context )
function
Type: Function()
The function whose context will be changed.
context
Type: PlainObject
The object to which the context (this) of the function should be set.

2)

jQuery.proxy( context, name )
context
Type: PlainObject
The object to which the context of the function should be set.
name
Type: String
The name of the function whose context will be changed (should be a property of the context object).

上面两个函数的作用是一样的,第一个函数的两个参数分别是:function指的是要调用的函数,context传递的是function中要设定并执行用到的参数。

第二个函数:第一个参数context是函数中要用到的参数,而第二个参数name是String类型并且指的是要执行的function的名称,所以跟第一个是 一样的,只是参数类型的不同。

个人认为还是第一个函数比较容易记忆,建议使用第一个参数。

然后举个例子:也是参照jquery官网的。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.proxy demo</title>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
  <p><button id="test">Test</button></p>
  <p id="log"></p>
 
<script>
var obj = {
  type: "John",
  test: function() {
    $( "#log" ).append( this.type );
    $( "#test" ).off( "click", obj.test );
  }
};
$( "#test" ).on( "click", jQuery.proxy( obj.test, obj ) );
</script>
 
</body>
</html>
上面的代码中如果点击了test按钮后,在id="log"的p标签中就会append上john。这就是在onclick事件中我们用jquery.proxy()方法对其中的对象进行了替换,默认执行的话this.type应该是button,就是说实际上上面的代码的执行的实际内容是这样的:

$("#test").on("click",function(){
    $("#log").append(obj.type);
    $( "#test" ).off( "click", obj.test );
});

如果绑定事件是这样写的话

$("#test").on("click",obj.test);
那么执行的方式肯定是:

$("#test").on("click",function(){
    $("#log").append($("#test").type);
    $( "#test" ).off( "click", obj.test );
});


那么最终的结果肯定添加的就是button了。

因为第二种用法跟第一种就是变量的写法不同,这里就不再详细说明了,大家可以自己试试。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值