has been on the use of JavaScript and call method used relatively vague, the previous period of time in the study of Angularjs source code, found that these two methods are very powerful, using a lot of scenes, here to do a summary.
Apply and call are applied to a method, except that apply has two parameters: Apply (Obj,args), where obj is the object used by the method, and args is the parameter array; call has multiple parameters, call (OBJ,ARG1,ARG2,ARG3 ...), obj is the same as apply obj, and the parameters are separated by commas, and the number of arguments is passed. As an example of apply, it is important to note that the second parameter of apply must be an array, otherwise an error will be made.
1.obj is null, undefined, bool value, 0, this, window, and so on, the equivalent of calling the method itself.
function test (ARG) {
Console.log (ARG);
}
Call Test.apply (null,[1,2,3]), test.apply (undefined,[1,2,3]), test.apply (false,[1,2,3]), test.apply (true,[1,2,3), respectively,
Test.apply (0,[1,2,3]), test.apply (this,[1,2,3]);
The output is 1.
The Ps:test function has only one parameter, so even if more than one parameter is passed into the array, it will only take the first one, and the others are ignored.
2.obj is an error when the object is not present. Still above one function for example.
Call Test.apply (ffff,[1,2,3]), then direct error.
Output: uncaught referenceerror:ffff is not defined.
3.obj is a function, such as xxx.apply (Obj,args), meaning to call the XXX function.
function Test1 (ARG) {
Console.log ("test1" + arg);
}
function Test2 (arg1, arg2) {
Console.log (Arg1 + "" + arg2);
}
Call Test1.apply (Test2, [1, 2, 3]);
Output: Test1 1.
As you can see, the argument is actually passed to Test1 and then called Test1.
4. When obj is an object, the Obj object overrides this of the XXX function in xxx.apply, which changes the property owned by this to the property of the Obj object itself.
Example 1:
function Test1 () {
Console.log ("Test1");
THIS.A = 1;
this.b = 2;
}
var c ={};
Test1.apply (c, []);
The C object at this time is {a:1,b:2}.
Example 2:
function Test1 () {
Console.log ("Test1");
THIS.A = 1;
this.b = 2;
}
Test1.prototype = {c:3, d:4};
var c = Test1.prototype;
Test1.apply (c, []);
The C object at this time is {a:1,b:2,c:3,d:4}.
Also, if the function has a return value, assign a variable to the result of the apply.
function Test1 () {
Console.log ("Test1");
return function () {
Console.log ("return function");
}
}
var back = test1.apply (null, []);
Back ();
Output: return function.
Now that you know about apply so much, call calls are similar, and you just need to change the array to a single comma-delimited argument. If you have other ways of using or find a problem, please enlighten me.
A detailed description of the application and call methods of JavaScript