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

1、基本定义和生成实例 函数

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

2、继承 (经过extends直接子类继承父类)this

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

  class Child extends Parent{

  }

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

  继承传递本身的参数(注意:能够使用super()来使用本身的属性,而且super必须放在第一行)es5

{
  // 继承传递参数
  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和setterspa

{
  // 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);
}

  静态方法和静态属性code

{
  // 静态方法 使用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);


}
相关文章
相关标签/搜索