es6学习笔记整理(十二)类和对象

类的概念

基本语法

类的基本定义和生成实例

class Parent{
    constructor(name='zhansan'){
        this.name = name;
    }
}
//生成实例
let v_parent = new Parent('lisi');//Parent {name: "lisi"}
console.log(v_parent);

类的继承
class Parent{
    constructor(name='zhansan'){
        this.name = name;
    }
}
//子类 继承extends
class Child extends Parent{

}

console.log(new Child());//Child {name: "zhansan"}

继承传参

            class Parent{
                constructor(name='zhansan'){
                    this.name = name;
                }
            }
            //子类 继承extends
            class Child extends Parent{
                constructor(name='child'){
                    super(name);//覆盖父级的属性,需要加上参数
                    //子类添加自己的属性,必须放在super()后面
                    this.type = 'child';
                }
            }

            console.log(new Child());//Child {name: "child", type: "child"}
静态方法

静态方法static:

  • 通过类调用,而不是通过类的实例去调用
 class Parent{
                constructor(name='zhansan'){
                    this.name = name;
                }

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

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

                static test(){
                    console.log('test');
                }
            }
            Parent.type = 'test1';

            console.log(Parent.type);//test1
getter\setter
            class Parent{
                constructor(name='zhansan'){
                    this.name = name;
                }
                //是属性,不是函数
                get firstName(){
                    return 'new:'+this.name;
                }
                set firstName(value){
                    this.name=value;
                }
            }

            var parent = new Parent();
            console.log(parent.firstName);//new:zhansan
            parent.firstName = 'lisi';
            console.log(parent.firstName);//new:lisi

你可能感兴趣的:(es6学习笔记整理(十二)类和对象)