This article mainly introduces the call and apply functions of Javascript, which are basically the same but slightly different, you can refer to the call method to call a function or method by using a specified this value and several specified parameter values.
Note:The syntax of this function is almost identical to that of the apply () method. The only difference is that the apply () method accepts an array of parameters while the call () method () the method accepts a list of parameters.
After understanding the concepts of these two methods, we can understand their applications step by step.
Change the point of this in the method.
Let's take a look at the example below.
Var name = "programmer"; var age = 1; var person = {name: "public number: bianchengderen", age: 20} function say () {console. log ("My name:" + this. name + ", age:" + this. age)} say (); // I am a programmer. age: 1say. call (person); // age: 20
The two invocation methods are different, and their results are different. The difference is that this in the say method points to different objects. The first invocation points to window, we use the call method to direct this in the say Method to the person object.
Is it a bit like someone else? What is the role of this? Of course, you can think about what you can do! Let's continue.
Implement Inheritance Mechanism
Inheritance, which is a feature of advanced object-oriented. With call, we can use JAVASCRIPT to have this feature.
Before reading the following example, you must understand the above example.
Function Person () {this. name = "programmer"; this. age = 20;} function Student () {Person. call (this); this. school = "Earth";} var student = new Student (); // print it out below: programmer, 20, Earth console. log (student. name, student. age, student. school );
In this example, the Student function inherits the name and age attributes of Person, that is, by using Person. call (this) is implemented. It is not difficult to understand the above example. student has the characteristics of Person and personality, such as this. school.
Here, we do not involve parameter transfer. It is easy for everyone to understand. We need to add parameter transfer. You can try the code and see how it works!
Let's talk about these two examples first, and then start further study.