I. Traditional PROTOTY inheritance
functionParent () { This. Name = "Thisisname";} Parent.prototype.sayName=function() { return This. Name;};functionChild () { This. Age = "Thisisage";} Child.prototype=Newparent ();/point to the parent instance (including the properties and prototypes of the instance) Child.prototype.constructor=Child ; Child.prototype.sayAge=function() { return This. Age;};varc =NewChild (); Console.log (c.name); Console.log (c.age); Console.log (C.sayname ()); Console.log (C.sayage () );
Two. Using object space inheritance
Creates a new constructor F, which is an empty object and hardly accounts for memory
functionChinese () {}chinese.prototype.nationality= "Chinese";
functionPerson (name, age) { This. Name =name; This. Age =Age ;}
functionF () {};//an empty object consumes little memoryF.prototype =Chinese.prototype;//point to the same prototype, affecting each other person.prototype=NewF ();// New after the address point to F.prototype,f.proptotype is also a point to the prototype address, so the operation Person.prototype will not affect the parent class prototype Person.prototype.constructor=Person ; Person.prototype.sayName=function() {//methods and properties in the prototype of a person need to be defined after inheritanceConsole.log ( This. name);};
varP1 =NewPerson ("Oli", 18); Console.log (p1.nationality); //ChineseP1.sayname ();//Oli
Add Chiness.call (this) if you want to inherit attributes from non-prototypes;
functionChinese () { This. HHH = ' HHH ';//New!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! This. Hello = ' Hello ';//New!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1}chinese.prototype.nationality= "Chinese";functionPerson (name, age) {Chinese.call ( This);//New!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! This. Name =name; This. Age =Age ;}functionF () {};//an empty object consumes little memoryF.prototype = Chinese.prototype;//point to the same prototype, affect each otherPerson.prototype =NewF ();//new After the address point to F.prototype,f.proptotype is also a point to the prototype address, so the operation Person.prototype will not affect the parent class prototypePerson.prototype.constructor =Person ; Person.prototype.sayName=function() {//methods and properties in the prototype of a person need to be defined after inheritanceConsole.log ( This. name);};varP1 =NewPerson ("Oli", 18); Console.log (p1.nationality); //ChineseP1.sayname ();//OliConsole.log (P1.HHH);//New!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Console.log (P1.hello);//New!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Recommended Links: 1190000004906911
Http://javascript.ruanyifeng.com/oop/pattern.html#toc0
JavaScript constructor inheritance