Home > Article > Web Front-end > What is the difference between call() and apply() methods?
This article mainly introduces the use of call() and apply() methods in JavaScript and the differences between them. It has certain reference value and I hope it will be helpful to everyone.
In JavaScript We often use two methods to change the pointer of this and simplify the complexity of the code. These two methods are the call() and apply() methods. Next, we will share their usage and differences
call() method
The first parameter in the call() method is to change the point of this, and the second parameter is the parameter that needs to be passed
<script> function Person(name, age,height){ this.name=name; this.age=age; this.height=height; } function Student(name,age,height,sex,grade){ Person.call(this,name,age,height);//将Person的参数传给Student this.sex=sex; this.grade=grade;} var student=new Student("张三",18,180,"男",88); </script> 运行结果:
apply() method
apply() method changes this pointer, the second value can only Pass an actual parameter and it is an array
<script> function Person(name, age,height){ this.name=name; this.age=age; this.height=height; } function Student(name,age,height,sex,grade){ Person.apply(this,[name,age,height]);//注意这儿传递的是数组 this.sex=sex; this.grade=grade;} var student= new Student("张三",18,180,"男",88); </script> 运行结果:
The difference between call() and apply() methods
The second value of the call() method can pass multiple parameters, and the actual parameters must be passed in accordance with the number and order of the formal parameters.
The second value of the apply() method only It must be an array to be able to pass, so the apply() method is suitable for using formal parameters that are arrays, and the call() method is suitable for passing continuous parameters
Summary: The above is the entire content of this article, I hope you all Pay attention to the choice of method when applying
The above is the detailed content of What is the difference between call() and apply() methods?. For more information, please follow other related articles on the PHP Chinese website!