JQuery. proxy (), accepts a function, returns a new function, and the new function always maintains a specific context.
JQuery. proxy (function, context)
The function that will change the context.
The context ('I') of the context function is set as this object.
JQuery. proxy (context, name)
The context of the context function is set as the object.
Name: name of the function to change the context (this function must be the attribute of the previous 'context' object)
This method is usually used when an event processing function is attached to an element, and the context actually points to another object.
In addition, jQuery ensures that, even if the function you bind is a function processed by jQuery. proxy (), you can still use the original function to correctly unbind the function.
Take a look at the official example:
Var obj = {
Name: "John ",
Test: function (){
Alert (this. name );
$ ("# Test"). unbind ("click", obj. test );
}
};
$ ("# Test"). click (jQuery. proxy (obj, "test "));
// The following code is equivalent to the above sentence:
// $ ("# Test"). click (jQuery. proxy (obj. test, obj ));
// Compare it with the following sentence.
// $ ("# Test"). click (obj. test );
Let's take a look at the jquery. proxy source code:
/* Proxy of jQuery source code:
Use the apply form to execute the callback function.
*/
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;
/* Conversion Result:
ThisObject-> context
Fn-> name
Proxy-> undefined
*/
}
// JQuery. proxy (name, context );
Else if (proxy &&! JQuery. isFunction (proxy )){
ThisObject = proxy;
Proxy = undefined;
}
}
If (! Proxy & fn ){
/* Use proxy to ensure that the context is the specified value during function execution */
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;
}
In fact, it is usually the call and apply, and most of the time it is used as the callback.