Home > Web Front-end > JS Tutorial > What do the apply() and call() methods do?

What do the apply() and call() methods do?

不言
Release: 2019-03-25 14:14:41
forward
2613 people have browsed it

The content of this article is about what the apply() and call() methods do? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Each function contains two non-inherited methods: apply() and call(). ;
Both call and apply are methods of Function.prototype, so each function instance has call and apply attributes;
Function

The call() method and the apply() method have the same effect : Change this pointer.

Difference

The difference lies in the way they receive parameters:
call(): The first parameter is that the this value has not changed, the change is that the other parameters are directly passed to the function. When using the call()
method, the parameters passed to the function must be listed one by one. Example: call(obj,a,b,c)
apply(): What is passed to the function is the parameter array. Example: apply(obj,[a,b,c])

Code:

function add(c, d){ 
    return this.a + this.b + c + d; 
} 
var o = {a:1, b:3}; 
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16  this指向o 
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34  this指向o
Copy after login

This article is over here, there are more For exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!

The above is the detailed content of What do the apply() and call() methods do?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template