JavaScript inheritance usually has three ways.
The first type: combined inheritance :
function Supertype (name) { This. Name =name; This. colors = ["Red","Blue","Green"]; } SuperType.prototype.sayName=function () {Console.log ( This. Name); }; Function subtype (name, age) {//invoke the Supertype constructor by calling () to inherit the Supertype propertySupertype.call ( This, name);//second call to Supertype () This. Age =Age ; } Subtype.prototype=NewSupertype ();//First time CallSubType.prototype.sayAge =function () {Console.log ( This. Age); }; varInstancel =NewSubtype ("Nicholas", A); Supertype ()
The inheritance inherits the method of the prototype chain through the constructor and the properties of the parent class, but the method will have two calls to the parent class, first in inheriting the prototype chain, and the second in inheriting the property.
The second type: prototype chain inheritance
//prototype Inheritance Instance code: functionCreateobj (o) {//performs a shallow copy of the incoming object functionF () {} F.prototype=o; return NewF (); } varperson ={name:"Tom", friends: ["One", "one", "Van"] }; varHups =createobj (person); Hups.name= "GRE"; HuPs.friends.push ("Rob."); varYeps =createobj (person); Yeps.name= "Lin"; YePs.friends.push ("Sari"); Console.log (person.friends);//"One,two,van,rob,sari"
This is nothing, JS's prototype inheritance feature.
The third type: parasitic inheritance
In the first method, when we first call the parent class, that is, when we inherit the prototype, we actually need a prototype copy of the parent class, and then we get the copy, which saves the call.
The inheritance technique is the most common.
functionInheritprototype (subtype, supertype) {varPrototype = object (Supertype.prototype);//create an object hyper-type prototype copyPrototype.constructor = subtype;//Enhanced objects Add construct properties to replicasSubtype.prototype = prototype;//Specifying Objects } functionsupertype (name) { This. Name =name; This. colors = ["Red", "Blue", "green"]; } SuperType.prototype.sayName=function() {Console.log ( This. Name); }; functionsubtype (name, age) {Supertype.call ( This, name); This. Age =Age ; } inheritprototype (subtype, supertype); SubType.prototype.sayAge=function() {Console.log ( This. Age); };
This article is referenced from https://my.oschina.net/quidditch/blog/307551
Javascript combination inherits prototype chain inheritance parasitic inheritance