美文网首页
ES6中的class

ES6中的class

作者: Grayly吖 | 来源:发表于2019-06-06 19:51 被阅读0次

    (在封装Koa时用到)

    一、class概述

    • class作为对象的模板被引入,可以通过class关键字定义类,通过new关键字实例化,它的本质是function

    二、基本语法

    1、匿名类

        let Person = class {
            constructor(a) {
                this.a = a;
            }
        }
    

    2、命名类

        class Person {
            constructor(name, age) {
                this.name = name;
                this.age = age;
            }
            speak() {
                //console.log(this);
                console.log('我的名字叫', this.name)
            }
        }
    

    3、注意事项

    • (1)类定义不会提升,必须在访问前对类进行定义,否则会报错

    • (2)类里面的方法不需要function关键字,且方法间不能用逗号隔开

    三、class继承

    1、通过extends实现类的继承

          class Child extends Person { ...}
    

    2、子类constructor方法中必须有super,且必须在this前用super

        class Child extends Person {
            constructor(name, age) {
                super(name, age);
                this.type= "child";
            }
        }
    

    四、class的实例化必须通过new关键字

    • 子类继承父类后可以调用父类中的方法
        let child = new Child("小明", 12);
        console.log(child);
        child.speak();
    

    每日额外

    (1)当类中的方法this指向反生改变时,可以在构造器中给该方法绑定this
    this.add = this.add.bind(this);

    class Electric extends Common {
        constructor() {
            super('Electric');
            this.add = this.add.bind(this);
        }
        // 增
        async add(ctx) {
           this.speak();
        }
    

    相关文章

      网友评论

          本文标题:ES6中的class

          本文链接:https://www.haomeiwen.com/subject/oquyxctx.html