Home > Article > Web Front-end > What do the apply() and call() methods do?
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
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!