ES6--類和對象

類的基本定義和生成實(shí)例

{
    //類的基本定義和生成實(shí)例
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
    }
    let v_parent=new Parent('v')
    console.log(v_parent)
    //Parent {name: "v"}
}

類的繼承以及子類繼承時修改父類傳下的默認(rèn)值

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

    }
    console.log(new Child())
    //Child {name: "muke"}
}
{
    //繼承傳遞參數(shù)
    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你好
}

靜態(tài)方法以及靜態(tài)屬性

{
    //靜態(tài)方法
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
        static tell(){
            console.log('tell')
        }
    }

    Parent.tell()
    //tell  注意:靜態(tài)方法只能是類調(diào)用,不能實(shí)例調(diào)用

}
{
    //靜態(tài)屬性
    class Parent{
        constructor(name='muke'){
            this.name=name;
        }
        static tell(){
            console.log('tell')
        }

    }
    Parent.type='test';
    console.log(Parent.type)
    //test 注意:靜態(tài)屬性只能是類調(diào)用,不能實(shí)例調(diào)用
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容