jQuery.proxy(),接受一個函數(shù),然后返回一個新函數(shù),并且這個新函數(shù)始終保持了特定的上下文(context )語境。
jQuery.proxy( function, context )
function將要改變上下文語境的函數(shù)。
context函數(shù)的上下文語境(`this`)會被設(shè)置成這個 object 對象。
jQuery.proxy( context, name )
context函數(shù)的上下文語境會被設(shè)置成這個 object 對象。
name將要改變上下文語境的函數(shù)名(這個函數(shù)必須是前一個參數(shù) ‘context’ 對象的屬性)
這個方法通常在向一個元素上附加事件處理函數(shù)時,上下文語境實際是指向另一個對象的情況下使用。
另外,jQuery 能夠確保即使你綁定的函數(shù)是經(jīng)過 jQuery.proxy() 處理過的函數(shù),你依然可以用原先的函數(shù)來正確地取消綁定。
看一下官方的例子:
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 ) );
// 可以與單獨執(zhí)行下面這句做個比較。
// $("#test").click( obj.test );
再看一下jquery.proxy的源碼:
/* jQuery 源碼之 proxy:
使用 apply 形式, 執(zhí)行回調(diào)函數(shù).
*/
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;
/* 轉(zhuǎn)化結(jié)果:
thisObject -> context
fn -> name
proxy -> undefined
*/
}
// jQuery.proxy(name, context);
else if ( proxy && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
}
if ( !proxy && fn ) {
/* 使用 proxy 保證 函數(shù)執(zhí)行時, 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,大部分的時候作為回調(diào)使用。