您的位置:首页 > Web前端 > JQuery

jquery的proxy方法的简单介绍

2014-08-19 14:04 211 查看
今天在代码中看到了这么一个方法$.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()方法对其中的对象进行了替换,就是说实际上上面的代码的执行的实际内容是这样的:
$("#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了。
因为第二种用法跟第一种就是变量的写法不同,这里就不再详细说明了,大家可以自己试试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: