ES5 constructor:
function F (name) { this . Name = name; // private property } f.prototype.writecss = function () {Console.log ( ' writecss '); // The method on the prototype "F.writejs = function () {// console.log (' js '
Class of ES6:
class f{ Constructor (name) {/// put private property, which is equivalent to the contents of the constructor in Es5 . Name = name; }; Writecss () {// method Console.log (' Writecss ') on the prototype ; } Static Writejs () { /// console.log (' JS ');} } New F (' Lily '); Console.log (f); F.writejs ();
Parasitic combination inheritance of ES5: (only the common attributes of the parent class can be inherited)
//Inherit only the public properties of the parent class
functionF (name) { This. Name =name; } f.prototype.writecss=function() {Console.log (' CSS '); } Let F=NewF (); //find on the instance first, if not, go to the prototype of the owning class by __proto__ //__proto__ is the key to implementing inheritance F class can find properties on the object class prototype, say inherit from ObjectConsole.log (F.hasownproperty (' name ')); Console.log (f.prototype.__proto__= = = Object.prototype);//true F class is a subclass of the object class, which can invoke properties on the prototype functionS (age) { This. Age = 20; } s.prototype = Object.create (f.prototype);//Parasitic combination inheritance ie6~8 not supported must precede the prototype Object!! S.prototype.writejs =function() {Console.log (' JS '); }; //The implementation of the S class is a subclass of Class F, and the S class can invoke the public property of Class F//s.prototype.__proto__ = F.prototype;Let S =NewS (); S.writecss ();
Call Inheritance for ES5: (Inherits the private property of the parent Class):
//inherit private properties of parent class functionF (name) { This. Name =name; } f.prototype.writecss=function() {console.log (' CSS ')); }; functionS (age, name) { This. Age = 20; F.call ( This , name); // this refers to an instance of S class S s.name= ' Lucy ' } s.prototype= Object.create (F.prototype);//Parasitic combination inheritance ie6~8 not supported must precede the prototype Object!! S.prototype.writejs =function() {console.log (' js ')); }; //implementing Class S is a subclass of Class F, and class S can invoke private properties of Class FLet S =NewS ("Lucy")); Console.log (s.name);
ES6 Inheritance: (Inherits private properties, common attributes, and static properties ):
class f{Constructor (name) { This. Name =name; //private Property } Writecss () {Console.log (' CSS '); //Public Properties } STATIC FN () {Console.log (' FN '); //static Properties } } class S extends f{//class S inherits from Class FConstructor (Age,name) {super (name); //If write extends then constructor must write Super (), equivalent to F.call (name) This. Age =Age ; } writejs () {Console.log (' JS '); }} let S=NewS ("Lucy")); Console.log (S.name); S.writecss (); S.fn ();
ES5 Constructors and ES6 classes