ES6-----学习系列十三(类与对象)

一、基本定义和生成实例 

{
  // 基本定义和生成实例
  class Parent{
    constructor(name='mukewang'){//构造器,初始化一些参数
      this.name=name;
    }
  }
  let v_parent=new Parent('v');
  console.log('构造函数和实例',v_parent);
}

二、继承 (通过extends直接子类继承父类)

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

  class Child extends Parent{

  }

  console.log('继承',new Child());
}

  继承传递自己的参数(注意:可以使用super()来使用自己的属性,并且super必须放在第一行)

{
  // 继承传递参数
  class Parent{
    constructor(name='mukewang'){
      this.name=name;
    }
  }

  class Child extends Parent{
    constructor(name='child'){
      super(name);
      this.type='child';
    }
  }

  console.log('继承传递参数',new Child('hello'));
}

  类中的getter和setter

{
  // getter,setter
  class Parent{
    constructor(name='mukewang'){
      this.name=name;
    }
  //注意下面的longName是属性而不是方法
    get longName(){
      return 'mk'+this.name
    }

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

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

  静态方法和静态属性

{
  // 静态方法 使用static声明 注意:静态方法只能通过类来调用,而不能通过类的实例进行调用,相当于es5中的私有方法
  class Parent{
    constructor(name='mukewang'){
      this.name=name;
    }

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

  Parent.tell();

}

{
  // 静态属性 直接类名通过.来声明一个静态属性
  class Parent{
    constructor(name='mukewang'){
      this.name=name;
    }

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

  Parent.type='test';

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


}
原文地址:https://www.cnblogs.com/diasa-fly/p/7017389.html