$.proxy( function, context ):
使用context代替function中的context。
比如:
var you = {
type: "person",
test: function(event) {
$("#log").append( this.type + " " );
}
}
$("#test").click(you.test);調(diào)用這句只有相當(dāng)于調(diào)用:
$("#test").click(function(event){
$("#log").append( this.type + " " );
});
所以這里的this指的是$("#test").
如果這樣調(diào)用:$("#test").click( $.proxy(you.test, you) );
此時的調(diào)用相當(dāng)于:
$("#test").click(function(event){
$("#log").append( you.type + " " );
});
雖然調(diào)用事件的對象是$("#test"),但是卻可以使用$.proxy把事件執(zhí)行內(nèi)的對象改變?yōu)閥ou。
$.proxy(context,functionname):
第一個參數(shù)是你想proxy的對象朝刊,第二個參數(shù)為要改變的函數(shù)的名字笼痹。
var obj = {
name: "John",
test: function() {
$("#log").append( this.name );
$("#test").unbind("click", obj.test);
}
};
$("#test").click( $.proxy( obj, "test" ) ); 把obj作為context傳入test中,而不是$("#test").
這個執(zhí)行完之后赂韵,結(jié)果會是John排截,
如果使用下面這句
$("#test").click(obj.test);
結(jié)果會是$("#test").的name值嫌蚤。