Look at the theoretical knowledge of the Apply function when it is very simple, but later to see the book a small code, found that there is no deep understanding of the function, here write down to make a note.
The code is as follows:
function r (x) {
return x;
}
function f (x) {
X[0] =x[0]+ ">";
return x;
}
function O () {
var temp = R;
R = function () {
Return temp.apply (this,f (arguments));
}
}
function A () {
O ();
document.write (r ("="));
}
for (var i = 0; I <10; i++) {
A ();
document.write ("</br>")
}
The results of the operation are as follows:
At first, I did not want to understand why printing = re-printing, and later on the code after the breakpoint processing, only to discover the mystery.
function r (x) {
document.write ("6");
return x;
}
function f (x) {
X[0] =x[0]+ ">";
document.write ("5");
for (var i = 0; i < arguments.length; i++) {
document.write (X[i]);
};
return x;
}
function O () {
var temp = R;
document.write ("1");
R = function () {
document.write ("4");
Return temp.apply (this,f (arguments));
}
document.write ("2");
}
function A () {
document.write (r ("="));
O ();
document.write ("3");
document.write (r ("="));
}
A ();
document.write ("<br><br>");
for (var i = 0; I <10; i++) {
A ();
document.write ("</br>")
// }
Following the instructions above, the code runs in this order:
Run O ()
Assign the R function to temp;
Print 1;
Rewrite R function, do not execute;
Print 2;
Back to a function, print 3;
Execute r ("=") function;
The R function is rewritten in O (), printing 4;
Returns a temp function
The return value. Execute f (arguments) First,
Printing 5
Because the arguments at this time is "=", the result of f ("=") is return = =
Execute function Temp (this, "=")
Printing 6
Back to =
So the final result is 123456=>.
Attention:
Temp = R is an assignment to a function;
R = function () {...} just wrote a function and did not call him, therefore do not execute the function;
If the first argument in the Apply function is this, that is, the function that calls him, if it is a different object or function, executes the object set by the first parameter, the second argument is an arguments array, and if it is a function, arguments is the return value of the function.
An instance of apply