国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > jquery > jQuery.proxy()代理、回调方法

jQuery.proxy()代理、回调方法

来源:程序员人生   发布时间:2014-01-09 08:00:05 阅读次数:2643次

jQuery.proxy(),接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文(context )语境。
jQuery.proxy( function, context )
function将要改变上下文语境的函数。
context函数的上下文语境(`this`)会被设置成这个 object 对象。
jQuery.proxy( context, name )
context函数的上下文语境会被设置成这个 object 对象。
name将要改变上下文语境的函数名(这个函数必须是前一个参数 ‘context’ 对象的属性)
这个方法通常在向一个元素上附加事件处理函数时,上下文语境实际是指向另一个对象的情况下使用。
另外,jQuery 能够确保即使你绑定的函数是经过 jQuery.proxy() 处理过的函数,你依然可以用原先的函数来正确地取消绑定。
看一下官方的例子:

var obj = {
name: "John",
test: function() {
alert( this.name );
$("#test").unbind("click", obj.test);
}
};

$("#test").click( jQuery.proxy( obj, "test" ) );

// 以下代码跟上面那句是等价的:
// $("#test").click( jQuery.proxy( obj.test, obj ) );

// 可以与单独执行下面这句做个比较。
// $("#test").click( obj.test );
再看一下jquery.proxy的源码:

/* jQuery 源码之 proxy:
使用 apply 形式, 执行回调函数.
*/
jQuery.proxy = function( fn, proxy, thisObject ) {
if ( arguments.length === 2 ) {
// jQuery.proxy(context, name);
if ( typeof proxy === "string" ) {
thisObject = fn;
fn = thisObject[ proxy ];
proxy = undefined;

/* 转化结果:
thisObject -> context
fn -> name
proxy -> undefined
*/
}
// jQuery.proxy(name, context);
else if ( proxy && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
}
if ( !proxy && fn ) {
/* 使用 proxy 保证 函数执行时, context 为指定值 */
proxy = function() {
return fn.apply( thisObject || this, arguments );
};
}
// Set the guid of unique handler to the same of original handler, so it can be removed
if ( fn ) {
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
}
// So proxy can be declared as an argument
return proxy;
}
其实就是平常使用的的call和apply,大部分的时候作为回调使用。

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生