The first actual parameter of call and apply is the parent object of the function to be called, which is the calling context. A reference to it is obtained through this in the function body.
For example, if you want to call function f as a method of object o, you can use the call and apply methods as follows:
f.call(o);
f.apply(o);
can be understood as follows :
o.m = f; // Store f as o Temporary method
o.m(); // Call this temporary method
delete o.m; // Delete this temporary method
Let’s give an example.
function testFun(){
return this.a this.b;
}
var o = {a:1, b:2};
testFun.call(o); //3
testFun.apply(o); //3
The execution results of the above code are all 3, which can be understood as return o.a o.b.
Consider a question, what if the first actual parameter of the call and apply methods is null or undefined? Let’s look at the following example:
var a = 10, b = 20;
function testFun(){
return this.a this.b;
}
testFun.call();
testFun.apply();
The results of the above code execution are all 30. This is because if the first actual parameter of call and apply is passed in as null or undefined, it will be replaced by the global object.
What is the difference between the two methods call and apply?
For the call method, all the actual parameters after the first calling context parameter are the values to be passed into the function to be called. For example, to call function f as a method of object o and pass in two parameters, you can use the following code:
f.call(o, 1, 2);
The apply method will all the actual parameters after the first actual parameter Put it into an array,
f.apply(o, [1, 2]);
Let’s give an example
function testFun(x, y){
return this.a this.b x y;
}
var o = {a:1, b:2};
testFun.call(o, 10, 20);
testFun.apply(o, [10, 20]);
The execution result of the above code is 33, which can be understood as return o.a o.b 10 20