In-depth Delegate class
Seeing some information on the Internet mainly AOL, it is still more specific, but there is a detail, I have never been very clear, so I want to write a little understanding of the Delegate class. The following is the code of the Delegate class:
Class mx.utils.delegate Extends Object
{
// Creating a static method of agency
Static Function Create (Obj: Object, Func: Function): Function
{
VAR f = function ()
{
Var Target = arguments.callee.target;
Var func = arguments.callee.func;
Return Func.Apply (Target, Arguments);
}
f.target = OBJ;
F.Func = func;
Return F;
}
// Proxy constructor
Function delegate (f: function)
{
Func = f;
}
PRIVATE VAR FUNC: FUNCTION;
// Non-static method creation agent.
Function CreateDelegate (OBJ: Object): Function
{
Return Create (Obj, FUNC);
}
}
The core code here is a Create static method, then what is the static method to do? The CREATE method must first pass two parameters, func and obj, OBJ specifies what makes funcs, specifies context for FUNC, saying that it is OBJ to specify the THIS reference in FUNC, this problem is in the previous example It is already very obvious. So how is the CREATE method did?
A function f is defined in the Create method.
VAR f = function ()
{
Var Target = arguments.callee.target;
Var func = arguments.callee.func;
Return Func.Apply (Target, Arguments);
}
It will be described here:
1, F declarged a Target variable, this variable is a context reference, as for the Target how to get this application key in its subsequent assignment statement: arguments.callee.target; and in the later CREATE method Statement: f.target = OBJ; there is a better understanding. The OBJ in which it is pasted into the CREATE method has been referenced by the target variable in the F function. Similarly, FUNC is also the same.
2. The FUNC is called in the function F, and the function f returns the return value of the function FUNC. Is this statement:
Return Func.Apply (Target, Arguments);
Finally, the Create method returned to F, so in fact, FUNC is inserted in the F function, so this can be obtained by the proxy function.
As for the other two dynamic methods to achieve the agent, the principle is the same. It must be introduced to OBJ and FUNC, just incoming at the same time.