Apply, call, and length attributes of the Function
JavaScript defines two methods for function objects: apply and call. They are used to bind the function to another object for running. The two methods are different only when defining parameters:
Function. prototype. apply (thisArg, argArray );
Function. prototype. call (thisArg [, arg1 [, arg2…]);
From the function prototype, we can see that the first parameter is named thisArg, that is, the this pointer inside all functions will be assigned thisArg, this achieves the purpose of running a function as another object. The two methods except the thisArg parameter are the parameters passed for the Function object. The following code illustrates how the apply and call methods work:
// Define A function func1 with the property p and method
Function func1 (){
This. p = "func1 -";
This. A = function (arg ){
Alert (this. p + arg );
}
}
// Define a function func2 with the property p and method B
Function func2 (){
This. p = "func2 -";
This. B = function (arg ){
Alert (this. p + arg );
}
}
Var obj1 = new func1 ();
Var obj2 = new func2 ();
Obj1.A ("byA"); // display func1-byA
Obj2. B ("byB"); // display func2-byB
Obj1.A. apply (obj2, ["byA"]); // display the func2-byA, where ["byA"] is an array with only one element, the same below
Obj2. B. apply (obj1, ["byB"]); // display func1-byB
Obj1.A. call (obj2, "byA"); // display func2-byA
Obj2. B. call (obj1, "byB"); // display func1-byB
It can be seen that after method A of obj1 is bound to obj2 for running, the runtime environment of function A is transferred to obj2, that is, this Pointer Points to obj2. Similarly, function B of obj2 can be bound to the obj1 object for running. The last four lines of the Code show the differences between the parameters of the apply and call functions.