The call method invokes a function or method under the premise of using a specified this value and several specified parameter values.
Note: The syntax of the function is almost identical to the syntax of the Apply () method, except that the Apply () method accepts a parameter array, and the call () method accepts a list of arguments.
After understanding the concepts of these two methods, let's take a step-by-step understanding of their applications.
Change the point of this within the method
Let's take a look at the following example
var name = "Programming Person";
var age = 1;
var person = {
Name: "Public Number: Bianchengderen",
age:20
}
function Say () {
console.log ("My Name:" + This.name+ ", Age:" +this.age)
}
say ();//My Name: Programmer, Age: 1
say.call (person);/Age: 20
The two invocations execute differently, and their results are different, not the same as this one in the say method points to the various objects, and the first execution points to window, and we execute by call, and the This in the say method points to the person object.
This is not a bit of pretending to be someone else's feeling. So what do we do? Of course, we can think more about what can be done! Let's go on down.
Implementing Inheritance Mechanisms
inheritance, which is an advanced object-oriented feature, with call we can have this feature of JavaScript.
Before you look at the following example, you must understand the above example.
function person () {
this.name = "programmer";
This.age =;
}
function Student () {
person.call (this);
This.school = "Earth";
}
var student = new Student ();
The following print out: Programming man, 20, earth
console.log (Student.name,student.age,student.school);
In this example, the student function inherits the name and age attribute of the person, which is accomplished by Person.call (this), and it should be easy to understand after understanding the example above. So student has the character of person and his own personality. , like this this.school.
Here, we do not involve the transfer of parameters, is convenient for everyone to understand, you need to add parameter transfer, you can knock code to try, see how the effect!
Let's talk about these two examples first, and then go deep into the study.