In actual projects, we usually use constructors to create an object and then add some commonly used methods to its prototype object. Finally, either instantiate the object directly, or use it as the parent class, declare an object, and inherit the parent class.
There are two common ways to inherit. Today we will discuss it briefly
The code copy is as follows:
//Premium class
function Person(name){
this.name = name;
};
// Subclass
function Student(sex){
Person.apply(this,arguments); //Inherit the constructor of the parent class
this.sex=sex;
};
1. Inherit Prototype:
The code copy is as follows:
Student.prototype = Person.prototype; //When executing this sentence, Student.prototype.constructor points to Person, why? Because Person.prototype.constructor points to Person, the assignment of the object is essentially a reference assignment, so Student.prototype.constructor also points to Person
Student.prototype.constructor = Student; // Refer to Student.prototype.constructor back to Person
Use Person's prototype object to overwrite Student's prototype object; the assignment of the object as mentioned earlier is essentially a reference assignment, so if any modification on Student.prototype will be reflected in Person.prototype, that is, the subclass will affect the parent class.
Look at the following:
The code copy is as follows:
Student.prototype.add=function(){alert("add")};
Person.prototype.add();//Popt add
2. Inheritance example:
The code copy is as follows:
Student.prototype = new Person(); //If no parameters are passed here, you can not write (); that is, write it directly as new Person;
2 Student.prototype.constructor = Student;
Use Person's instance to overwrite the Student's prototype object; creating an instance, compared to the previous one, it is a waste of memory, but this also solves the disadvantage of the above method, that is, any modifications on Student.prototype at this time It will not be reflected in Person.prototype, that is, the subclass will not affect the parent class.
3. Use control objects to combine the advantages of 1 and 2 to eliminate the disadvantages
The code copy is as follows:
var F = function(){};
F.prototype = Person.prototype;
Student.prototype = new F();
Student.prototype.constructor = Student;
F is an empty object, with only some prototype methods above, which consume less memory when instantiating, and also isolates the impact of subclasses on parent classes.