ES6新特性使用小结(五)

十二、class 与 extends

 ①、类的基本定义和生成实例

{   
    class Parent{
        constructor(name='Lain'){          //定义构造函数
            this.name = name;
        }
    }
    let a = new Parent('Mayu');   //生成实例
    console.log(a);             //Parent {name: "Mayu"}

    //继承
    class Child extends Parent{         //通过 关键字 extends    实现继承

    }
    let b = new Child();
    console.log(b)      //Child {name: "Lain"}      继承了Parent 并使用了Parent的默认值
}

②、通过 extends 实现继承

{
    class Parent{
        constructor(name='Lain'){
            this.name = name;
        }
    }
    //继承
    class Child extends Parent{         //通过 关键字 extends    实现继承
        constructor(name='child'){      //定义了子类的默认值
            super(name);                //使用 super方法传递参数
            this.type='child';          //      **在继承关系中 如果使用了super 一定要将 super方法放在第一行
        }
    }
    let b = new Child();
    console.log(b)      //Child {name: "child", type: "child"}      继承了Parent 并使用了Child的默认值
}

③、class 中的 getter 和 setter

{   
    class Parent{
        constructor(name='Lain'){
            this.name = name;
        }
        get longName(){         //  ** 这里是属性 而不是方法
            return  'Hello '+this.name;
        }
        set longName(value){
            this.name =value;
        }
    }

    let c = new Parent();
    console.log('getter',c.longName);   //getter    Hello Lain
    c.longName = 'abc';
    console.log('setter',c.longName);     //setter Hello abc
}

④、class 中的 静态方法

{   
    class Parent{
        constructor(name='Lain'){
            this.name = name;
        }

        static tell(){          //  使用 关键字 static 定义静态方法
                                //  ***  该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
            console.log('static');
        }
    }
    Parent.tell();      //static
}

⑤、class 中的 静态属性

{   
    class Parent{
        constructor(name='Lain'){
            this.name = name;
        }

        static tell(){
            console.log('static');
        }
    }
    Parent.type  ='test';           // 在 class 定义完毕后 在 类 上直接定义 静态方法 而不是在实例上
    console.log('静态属性',Parent.type);        //静态属性 test
}
原文地址:https://www.cnblogs.com/sunyaaa/p/7683686.html