In actual projects, we usually use a constructor to create an object, and then add some common methods to its prototype object. Finally, either instantiate the object directly, or use it as a parent class, declare an object, and inherit the parent class.
There are two commonly used methods when inheriting. Today we will discuss a little bit
//Parent 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:
Student.prototype = Person.prototype; //When this sentence is executed, Student.prototype.constructor points to Person. Why? Because Person.prototype.constructor points to Person, object assignment is essentially reference assignment, so Student.prototype.constructor also points to Person
Student.prototype.constructor = Student; // Point Student.prototype.constructor back to Person
Use Person’s prototype object to overwrite Student’s prototype object; as mentioned earlier, object assignment is essentially reference assignment, so if any modifications on Student.prototype will be reflected in Person.prototype, that is Subclasses affect parent classes.
Look below:
Student.prototype.add=function(){alert( "add")};
Person.prototype.add();//Pop up add
2. Inherited instance:
Student.prototype = new Person(); //If no parameters are passed here, you don’t need to write (); that is, write directly new Person;
2 Student.prototype.constructor = Student;
Use Person instance to overwrite the prototype object of Student; creating an instance is a waste of memory compared to the previous one, but this also solves the shortcomings of the above method, that is, any modifications on Student.prototype will not be reflected at this time to Person.prototype, that is, the subclass will not affect the parent class.
3. Use control objects 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 some prototype methods on it , takes up less memory during instantiation, and also isolates the impact of the subclass on the parent class.