Home > Article > Web Front-end > The relationship between class and js prototype prototype inheritance in ES6
ES6 introduces the keyword class in order to further reduce code writing and simplify code logic. But the implementation of class is also based on prototype, with a layer of syntactic sugar. Most of its functions can be achieved by ES5. The new class writing method only makes the writing method of object prototype clearer and more like object-oriented programming. Just grammar.
class Person { constructor(name) { this.name=name||"Default"; } toString(){ return 'Name:'+this.name; } } var p1=new Person(); console.log(p1.name); class Boy extends Person{ constructor(name){ super(name); this.gende='Boy'; } toString(){ return super.toString()+" - Gende:"+this.gende; } } var b1=new Boy('hello'); console.log(b1); console.log(b1.toString());
Inheritance of ES5, that is, prototype
The essence is to first create the instance object this
of the subclass and then add the methods of the parent class to this (Parent. apply(this))
ES6 inheritance, that is, class
The essence is to first create the instance object this of the parent class (super must be called first)
and then use the constructor of the subclass to modify this
Their implementation mechanisms are different.
ES6 is the same as ES5. All instances of a class share a prototype object.
For es6, it is still necessary to read the documentation.
Related recommendations:
Detailed explanation of the class keyword in ES6
Examples of usage of get and set of the class class in ES6 javascript
Detailed explanation of the usage of Prototype attribute of js
The above is the detailed content of The relationship between class and js prototype prototype inheritance in ES6. For more information, please follow other related articles on the PHP Chinese website!