ES6(类)

一、类的基本定义和生成实例
{
    // 基本定义和生成实例
    class Parent {
        constructor(name = 'parent') {
            this.name = name;
        }
    }

    // 创建类的实例
    let v_parent = new Parent('v');
    console.log('构造函数和实例', v_parent);
}
二、继承
{
    // 继承 通过extends关键字
    class Parent {
        constructor(name = 'parent') {
            this.name = name;
        }
    }

    class Child extends Parent {
    }

    console.log('继承', new Child());
}
三、继承传递参数

在子类中利用super(),将参数传递进去可覆盖父类中的值

{
    // 继承传递参数
    class Parent {
        constructor(name = 'parent') {
            this.name = name;
        }
    }

    class Child extends Parent {
        constructor(name = 'child') {
            //将子类的name传递进去,覆盖父类中的name
            // 注意:super要放在第一行
            super(name);
            this.type = 'child type'
        }
    }

    console.log('继承传递参数', new Child());
}
四、类的getter setter方法
{
    // getter setter
    class Parent {
        constructor(name = 'parent') {
            this.name = name;
        }

        get longName() {
            return 'mk' + this.name;
        }

        set longName(value) {
            this.name = value;
        }
    }

    let v = new Parent();
    console.log('getter', v.longName);

    v.longName = 'hello';
    console.log('setter', v.longName);
}
五、静态方法 static

静态方法:通过static修饰的方法

{
    // 静态方法 static
    class Parent {
        constructor(name = 'parent') {
            this.name = name;
        }

        static tell() {
            console.log('tell');
        }

    }

    // 静态方法 只能通过类调用,不能通过类的实例去调用
    Parent.tell();

    //以下这种写法不正确
    // let v=new Parent();
    // v.tell();
}
六、静态属性
{
    // 静态属性
    class Parent {
        constructor(name = 'parent') {
            this.name = name;
        }

        static tell() {
            console.log('tell');
        }
    }

    //直接在类上定义,通过这种方式实现静态属性
    Parent.type = 'test';
    //读取时,直接调用Parent.type
    console.log('静态属性', Parent.type);
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容