The Class keyword and super() method in ES6, using detailed (class class and super() method)

Introduction: In ES6, we can use the class keyword to define a class, and implement class inheritance through the extends keyword, and then in a subclass, we can use the super() keyword to call the constructor of the parent class; today Share the details of the use of the class keyword.

1. First, use the class keyword to define a parent class;

这里定义一个名为Fatherfn的class类,类名字首字母要大写

class Fatherfn{ 

    constructor是默认构造方法,不能修改
    constructor(name) { 
        this.name = name;
                     }
    父类中的eat()方法
    eat() { 
        console.log(`${this.name} is eating.`);
        }

   }

2. Then define a subclass, and inherit the parent class named Fatherfn through the extends and super() methods ;

这里再定义一个名为Son的class类,并通过extends继承上面名为Fatherfn的类

这里继承extends Fatherfn ,继承父类属性
class Son extends Fatherfn { 

        constructor是默认构造方法,不能修改
        constructor(name, hobby) {
                结合super()方法, 可以继承调用父类的构造函数
                super(name); 
                this.hobby= hobby;
                                 } 
        子类中的drink()方法 
        drink() { 
                console.log(`${this.name} is drinking.`); 
                } 

    }

3. Finally, create an instance object of a subclass;

const demoFn= new Son("Buddy", "study");

// 调用子类的方法 
demoFn.eat(); 
// 输出:Buddy is eating. 

demoFn.drink(); 
// 输出:Buddy is drinking.

可以看到这里既可以使用父类函数中的eat()方法,也可以使用子类函数中的drink()方法。

Precautions:

  1. The class keyword, the named function, the first letter of the name should be capitalized (required, but not mandatory);
  2. Each class class has a constructor construction method, and the name of this method cannot be modified;
  3. In the class class, the function() method of es5 cannot be used;

Summarize:

1. The class class inheritance and super() usage in ES6 can realize the inheritance relationship between classes, and then through the extends keyword, subclasses can inherit the properties and methods of the parent class.

2. In the constructor of the subclass, use the super() keyword to call the constructor of the parent class and pass the corresponding parameters. In this way, code reuse and extension can be realized, and code readability and maintainability can be improved.

Guess you like

Origin blog.csdn.net/weixin_65793170/article/details/131458630