Home >Web Front-end >JS Tutorial >A brief discussion on call and apply methods in javascript_javascript skills

A brief discussion on call and apply methods in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:21:191149browse

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:

Copy code The code is as follows:

 f.call(o);
 f.apply(o);

can be understood as follows :
Copy code The code is 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.
Copy code The code is as follows:

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:
Copy the code The code is as follows:

 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:
Copy code The code is as follows:

 f.call(o, 1, 2);

The apply method will all the actual parameters after the first actual parameter Put it into an array,
Copy code The code is as follows:

 f.apply(o, [1, 2]);

Let’s give an example
Copy code The code is as follows:

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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn