Classes and instances
Classes and inheritance: How to implement inheritance, several ways of inheriting
The first: implementing inheritance with the help of constructors
function Parent1 () { this. Name = ' Parent1 ';} function Child1 () {parent1.call (this// ) is the constructor that executes the parent, or you can use apply to change the context this . Type = ' Child1 ';} New Child1 ();
Disadvantage: Parent1 's prototype above attribute or method cannot be inherited by CHLID1, only partial inheritance is realized.
Second: Using the prototype chain for inheritance
function Parent2 () { this. Name = ' Parent2 ';} function Child2 () { this. Type =new Parent2 (); New Chlid2 ();
disadvantage (problem): New attributes are added to the parent class, so all instances change at the same time. If the attribute value (from the parent class) of an instance changes, the other instances change as well. Because all instances of __proto__ are the same, there is an effect on each other.
The Third Kind: combination mode
function Parent3 () {this.name = ' parent3 '; This.play = [1,2,3,4];} function Child3 () {parent3.call (this); This.type = ' child3 ';} Child3.prototype = new Parent3 (), var s3 = new Child3 (), var s4 = new Child3 ();
disadvantage: The parent's constructor executes two times, but it is not necessary.
Fourth: Optimization of combinatorial inheritance 1
function Parent4 () {this.name = ' parent4 '; This.play = [1,2,3,4];} function Child4 () {parent4.call (this); This.type = ' child4 ';} Child4.prototype = Parent4.prototype;var S5 = new Child4 (), var s6 = new Child4 (); S5 instanceof Child4 ======>>>t RUES5 instanceof Parent4 ======>>>true
question: How to distinguish whether an object is instantiated by a subclass or is instantiated by a parent class (direct instantiation)
The constructor method is problematic here because s5.constructor points to Parent4. (In fact, the previous method also has this problem)
Fifth: Optimization of combinatorial inheritance 2
function Parent5 () {this.name = ' parent5 '; This.play = [1,2,3,4];} function Child5 () {parent5.call (this); This.type = ' child5 ';} Child5.prototype = Object.create (Parent5.prototype); Child5.prototype.constructor = Child5;var s7 = new Child5 (); var s8 = new Child5 ();
Web Front end interview (V): Object oriented