JQuery.proxy(function,context):
使用context代替function中的context。
比如:
var you = {
type: "person",
test: function(event) {
$("#log").append( this.type + " " );
}
$("#test").click(you.test);調用這句只有相當於調用:
$("#test").click(function(event){
$("#log").append( this.type + " " );
});
所以這裏的this指的是$("#test").
如果這樣調用:$("#test").click($.proxy(you.test,you));
此時的調用相當於:
$("#test").click(function(event){
$("#log").append( you.type + " " );
});
雖然調用事件的對象是$("#test"),但是卻可以使用$.proxy把事件執行內的對象改變爲you。
JQuery.proxy(context,functionname):
第一個參數是你想proxy的對象,第二個參數爲要改變的函數的名字。
var obj = {
name: "John",
test: function() {
$("#log").append( this.name );
$("#test").unbind("click", obj.test);
}
};
$("#test").click( jQuery.proxy( obj, "test" ) ); 把obj作爲context傳入test中,而不是$("#test").
這個執行完之後,結果會是John,
如果使用下面這句
$("#test").click(obj.test);
結果會是$("#test").的name值。
這個函數和上面的那個函數的功能一樣,就是使用了更加簡潔的方式。
轉自 http://www.cnblogs.com/acles/archive/2012/11/20/2779282.html