The two methods of js prototype inheritance are compared and introduced

  • 2020-03-30 02:28:48
  • OfStack

In real projects, we usually create an object with a constructor and add some common methods to its prototype object. Finally, either instantiate the object directly, or declare it as a parent, and then declare an object that inherits the parent.

There are two common ways of inheritance, and today we're going to talk a little bit about it

// The parent class 
 function Person(name){ = name;
 //  A subclass 
 function Student(sex){
  Person.apply(this,arguments); //Inherits the constructor of the parent class;

1. Inherit Prototype:

Student.prototype = Person.prototype; //After this sentence, the Student. The prototype. The constructor is pointing to the Person, why? Because of the Person. The prototype. The constructor to Person, object assignment is essentially reference assignment, so Student. The prototype. The constructor also points to the Person
Student.prototype.constructor = Student;  //  The Student. The prototype. The constructor refers back to the Person

Use the prototype object of Person to override the prototype object of Student; As mentioned earlier, the assignment of an object is essentially a reference assignment, so if any changes on student.prototype are reflected in person.prototype, the subclass will affect the parent class.

See the following:

Person.prototype.add();//Pop up the add

2. Inheritance instance:

Student.prototype = new Person();  //If no parameter is passed here, no () can be written; I'm just going to say new Person;
2 Student.prototype.constructor = Student;

Override the Student prototype object with an instance of Person; The instance is created, and the display is a waste of memory compared to the previous one, but it also solves the shortcoming of the above method, that is, any changes on student.prototype will not be reflected in person.prototype, that is, the subclass will not affect the parent class.

3. Use the control object to combine the advantages of 1 and 2 and remove the disadvantages

var  F = function(){};
F.prototype = Person.prototype;
Student.prototype  = new F();
Student.prototype.constructor  = Student;

F is an empty object with only a few prototype methods, which take less memory to instantiate, and also insulate the subclass from its parent.

Related articles: