ES6学习笔记四(类和对象)

{
    // 构造函数和实例
    class Parent{
        constructor(name='mukewan'){
            this.name=name;
        }
    }
    let v_parent=new Parent('v');
    console.log('构造函数和实例',v_parent);   //构造函数和实例 Parent {name: "v"}
}

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

    class Child extends Parent{

    }
    console.log('继承',new Child());  //继承 Child {name: "mukewan"}
}
{
    // 继承传递参数
    class Parent{
        constructor(name='mukewan'){
            this.name=name;
        }
    }

    // 子类Child继承父类Parant
    class Child extends Parent{
        constructor(name='child'){
            super(name);  //修改父类属性,一定要放在构造函数的第一行
            this.type='child';
        }
    }

    console.log('继承传递参数',new Child('hello'));  //继承传递参数 _Child {name: "hello", type: "child"}
}

getter(读取)、setter(设置)属性

{
    // getter,setter
    class Parent {
        constructor(name='mukewan'){
            this.name=name;
        }

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

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

    let v=new Parent();
    console.log('getter',v.longName);  // getter mkmukewan
    v.longName='hello';
    console.log('setter',v.longName);  //setter mkhello
}

static静态方法跟静态属性

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

        static tell(){  //static+函数名,
             console.log('tell');   
        }        
    }

    Parent.tell();  //tell  静态方法是通过类去调用,而不是实例去调用!

}

{
    // 静态属性
    class Parent {
        constructor(name='mukewan'){
            this.name=name;
        }

        static tell(){  //static+函数名,
             console.log('tell');   
        }        
    }

    Parent.type='test'  //这边使用的都是类,而不是实例

    console.log('静态属性',Parent.type);  //静态属性 test

}
原文地址:https://www.cnblogs.com/qdlhj/p/9930878.html