In es6, inheritance can be achieved using the class keyword and the extends keyword. The class keyword was introduced in ES6 to declare a class, and a class (class) can inherit the properties and methods of the parent class through extends. The syntax is "class subclass name extends parent class name {...};".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
In ES6, you can use the class keyword together with the extends keyword to implement inheritance.
In ES6, class (class) is introduced as a template for an object, and you can use class Keywords define classes.
es6 inheritance
Class can be inherited through the extends keyword
class Animal {} class Cat extends Animal { };
The above code defines a Cat class, which inherits all properties and methods of Animal class through the extends keyword. But since no code is deployed, the two classes are exactly the same, which is equivalent to copying an Animal class. Next, we add code inside Cat.
class Cat extends Animal { constructor(name, age, color) { // 调用父类的constructor(name, age) super(name, age); this.color = color; } toString() { return this.color + ' ' + super.toString(); // 调用父类的toString() } }
The super keyword appears in both the constructor method and the toString method. It represents the constructor of the parent class here and is used to create a new this object of the parent class.
It should be noted that the class keyword is just syntax sugar for prototype, and JavaScript inheritance is still implemented based on prototype.
class Pet { constructor(name, age) { this.name = name; this.age = age; } showName() { console.log("调用父类的方法"); console.log(this.name, this.age); } } // 定义一个子类 class Dog extends Pet { constructor(name, age, color) { super(name, age); // 通过 super 调用父类的构造方法 this.color = color; } showName() { console.log("调用子类的方法"); console.log(this.name, this.age, this.color); } }
Advantages:
Clear and convenient
javascript video tutorial, web front-end】
The above is the detailed content of What is the way to implement inheritance in es6. For more information, please follow other related articles on the PHP Chinese website!