ES6--类和对象

类的基本定义和生成实例

{
    //类的基本定义和生成实例
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
    }
    let v_parent=new Parent('v')
    console.log(v_parent)
    //Parent {name: "v"}
}

类的继承以及子类继承时修改父类传下的默认值

{
    //继承
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
    }
    class Child extends Parent{

    }
    console.log(new Child())
    //Child {name: "muke"}
}
{
    //继承传递参数
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
    }
    //子类向父类传递
    class Child extends Parent{
        constructor(name='child'){
            super(name);
            this.type='child'//this一定要放在super之后
        }
    }
    console.log(new Child())
    //_Child {name: "child", type: "child"}
}

类的getter和setter方法

{
    //getter,setter
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
        get longName(){
            return 'mk'+this.name;
        }

        set longName(value){
            this.name=value;
        }
    }
    let v=new Parent();
    console.log(v.longName)
    //mkmuke
    v.longName='你好';
    console.log(v.longName)
    //mk你好
}

静态方法以及静态属性

{
    //静态方法
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
        static tell(){
            console.log('tell')
        }
    }

    Parent.tell()
    //tell  注意:静态方法只能是类调用,不能实例调用

}
{
    //静态属性
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
        static tell(){
            console.log('tell')
        }

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

相关阅读更多精彩内容

友情链接更多精彩内容