Reference: https://www.imooc.com/article/17389
Https://www.cnblogs.com/chenyangsuaige/p/6130737.html
Inheritance can be well encapsulated, subclasses can reuse the methods of the parent class directly, and add their own properties and methods.
The prototype object prototype is a unique identifier for the class, and the inheritance of the class is based on prototype.
Inheritance of classes in ES5
//Inheritance of the ES5 class four parts//1. Create a parent classfunctionParent (name) { This. Name =name;} Parent.prototype.location= "Earth"; Parent.prototype.getName=function() {Console.log ( This. name);}//2. Creating subclassesfunctionSon (name,age) {Parent.call ( This, name);//subclass calls the constructor of the parent class This. Age =Age ;}//3. Create inheritance, the prototype object of a subclass is an instance of the parent classSon.prototype =NewParent ();//here Son.prototype._proto_=parent.prototype,son.prototype.constructor=parent//correcting the constructor of subclassesSon.prototype.constructor =Son;//4. Adding child class membersSon.prototype.id = 123; Son.prototype.getAge=function() {Console.log ( This. age);}//Create an instancevarStudent1 =NewSon (' ASD ', ' 11 '); Student1.getname ();//ASD, a method inherited from a parent classStudent1.getage ();//11, subclasses of their own methods
Inheritance of classes in ES6
//class and inheritance in Es6//creating a parent classclass parent{Constructor (name) { This. Name =name; }//!! Note that there are no commas hereGetName () {Console.log ( This. Name); }}
//Child class inherits from parent classclass Son extends parent{constructor (Name,age) {super (name);//super points to the instance object of the parent class,calling the constructor of the parent class, you must call the Super method before the subclass can use this This. Age = Age;//subclasses inherit the This object of the parent class and modify the} getName () {super.getname ();//calling a method of the parent classConsole.log (' son '); }}
Attention:
1, the Es6 class can only define constructor properties and methods, the method is all defined in the prototype of the class, and the method is not enumerable;
2. The constructor property of a class in ES6 is equivalent to a constructor in es5, and if no constructor attribute is defined, an empty constructor is added by default;
3,es5 , inheritance is a subclass that first creates its own instance object this, and then invokes the method of the parent class through Parent.call (this) or parent.apply (this);es6 , inheritance is The parent class first creates its own instance object this, and then the subclass inherits this from the parent class and modifies this in the constructor of the subclass.
Class and inheritance in the ES6 of JavaScript