In actual projects, we usually use constructors to create an object, and then add some common methods to its prototype object. Finally, you can either directly instantiate the object, or use it as the parent class, and then declare an object to inherit the parent class.
There are two common methods for inheritance. Today we will discuss it a bit.
Copy codeThe Code is as follows:
// Parent class
Function Person (name ){
This. name = name;
};
// Subclass
Function Student (sex ){
Person. apply (this, arguments); // inherits the constructor of the parent class.
This. sex = sex;
};
1. inherit Prototype:
Copy codeThe Code is as follows:
Student. prototype = Person. prototype; // when this sentence is executed, Student. prototype. constructor points to Person. Why? Because Person. prototype. constructor points to Person, the object Value assignment is essentially a reference value assignment, so Student. prototype. constructor also points to Person
Student. prototype. constructor = Student; // point Student. prototype. constructor back to Person
The prototype object of Person is used to overwrite the prototype object of Student. As mentioned above, the object assignment is essentially a reference assignment, so if Student. any modifications made to prototype will be reflected in Person. prototype, that is, subclass affects the parent class.
See the following:
Copy codeThe Code is as follows:
Student. prototype. add = function () {alert ("add ")};
Person. prototype. add (); // The add
2. inherited instances:
Copy codeThe Code is as follows:
Student. prototype = new Person (); // if no parameter is passed here, You can directly write it as new Person;
2 Student. prototype. constructor = Student;
The Person instance is used to overwrite the prototype object of Student. The created instance is a waste of memory compared to the previous one, but it also solves the disadvantages of the above method, student. any modifications to prototype will not be reflected in Person. in prototype, that is, subclass does not affect the parent class.
3. Use the control object to combine the advantages of 1 and 2 to remove the disadvantages.
Copy codeThe Code is as follows:
Var F = function (){};
F. prototype = Person. prototype;
Student. prototype = new F ();
Student. prototype. constructor = Student;
F is an empty object. There are only some prototype methods above. The memory usage is small during instantiation, and the impact of subclass on the parent class is also isolated.