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 parent class
function person (name) {
this.name = name;
};
Subclass
function Student (sex) {
person.apply (this,arguments);//Inheriting the constructor of the parent class
This.sex=sex;
1, Inherit prototype:
1 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
2 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.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/
Look below:
1 student.prototype.add=function () {alert ("Add")};
2 Person.prototype.add ()//Popup add
2, inheriting instances:
1 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
1 var F = function () {};
2 F.prototype = Person.prototype;
3 Student.prototype = new F ();
4 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.
Author: cnblogs Wimber