In actual projects, we usually use constructors to create an object and then add some common methods to its prototype object. Finally either instantiate the object directly, or use it as the parent class, and then declare an object that inherits the parent class.
And there are two common ways of inheriting, and today we're going to have a little discussion.
Copy Code code as follows:
Parent class
function person (name) {
THIS.name = name;
};
Sub Class
function Student (Sex) {
Person.apply (this,arguments); Inheriting constructors of parent classes
This.sex=sex;
};
1, Inherit prototype:
Copy Code code as follows:
Student.prototype = Person.prototype; After executing this sentence, Student.prototype.constructor points to person, why? Because Person.prototype.constructor points to person, the assignment of an object is essentially a reference assignment, so Student.prototype.constructor also points to the person
Student.prototype.constructor = Student; Refer Student.prototype.constructor back to person
Overwriting a student prototype object with a person's prototype object; the assignment of an object is essentially a reference assignment, so if any changes on the Student.prototype are reflected in Person.prototype, the subclass affects the parent class.
Look below:
Copy Code code as follows:
Student.prototype.add=function () {alert ("Add")};
Person.prototype.add ()//Popup add
2, inheriting instances:
Copy Code code as follows:
Student.prototype = new Person (); If the parameter is not passed here, it can be written without (), i.e. directly written as new person;
2 Student.prototype.constructor = Student;
Overwriting a student prototype object with an instance of person; Creating an instance that shows a waste of memory compared to the previous one, but it also solves the drawbacks of the method above. That is, any changes on Student.prototype are not reflected in the person.prototype, that is, subclasses do not affect the parent class.
3, using the control object to combine the advantages of 1 and 2, remove the disadvantage
Copy Code code as follows:
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, with less memory footprint when instantiated, and also from the effect of subclasses on the parent class.