This article mainly introduced the JS prototype inheritance of two methods of comparison, the need for friends can refer to the
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.
The code is 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:
The code is 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:
The code is as follows:
Student.prototype.add=function () {alert ("Add")};
Person.prototype.add ()//Popup add
2, inheriting instances:
The code is 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
The code 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 a few prototype methods, with less memory footprint when instantiated, and also from the effect of subclasses on the parent class.