Combined Inheritance: class inheritance is used in combination with constructor inheritance, but there is a problem that the subclass is not an instance of the parent class, and the child class is a prototype of the parent class, so the parasitic combined inheritance.
That is to say, parasitic is parasitic inheritance, parasitic inheritance is based on prototype inheritance, prototype inheritance and class inheritance is similar, so another inheritance pattern should be constructor inheritance. Of course, the problem with subclasses that are not instances of the parent class is caused by class-type inheritance.
Speaking of which, I have to say, Brother Douglas's transformation of parasitic inheritance
function Inheritprototype (subclass,superclass) { // Copy a copy of the prototype of the parent class is saved in the variable var p = Inheritobject (superclass.prototype); // Fix the construction property of a subclass is modified because the subclass prototype is overridden P.constructor = subclass; // set up a prototype for a subclass Subclass.prototype = p;}
What we need is that inheritance is just a prototype of the parent class, and we no longer need to invoke the constructor of the parent class.
Test it.
//defining the Parent classfunctionSuperclass (name) { This. Name =name; This. colors = [' Red ', ' blue ', ' green '];}//How to define a parent class prototypeSuperClass.prototype.getName =function() {Console.log ( This. name);}//Defining subclassesfunctionSubclass (Name,time) {//constructor-style inheritanceSuperclass.call ( This. Name); //sub-class new properties This. Time =Time ;}//parasitic inheritance of parent class prototypesInheritprototype (subclass,superclass);//New prototype method for sub-classSubClass.prototype.getTime =function(Time) {Console.log ( This. time);}//Create two test methodsvarInstance1 =NewSubclass (' JS book ', 2014);varInstance2 =NewSubclass (' CSS book ', 2013);
We first create the parent class, and the prototype method of the parent class,
It then creates the subclass and implements the constructor-style inheritance in the constructor.
Then the parent prototype is inherited by the parasitic type,
Finally, some prototype methods are added to the sub-class.
Instance1.colors.push (' black '); Console.log (instance1.colors); // [' Red ', ' blue ', ' green ', ' black '] // [' Red ', ' blue ', ' green ']instance1.getname (); // CSSbook instance2.gettime (); // -
Note: A subclass that wants to add a prototype method must pass a prototype object, one way to add it through the form of a point syntax, or it will be directly assigned to an object that overrides the inherited object from the parent class prototype.
Object-oriented programming of JavaScript design patterns (object-oriented programming,oop)-Parasitic combined inheritance