ES6 的类和对象的简单解析

{
  // 一个类的基本定义和生成实例
  // 定义一个Parent类
  class Gfriend{
    // 构造函数
    constructor(name='甜甜圈'){
      this.name=name;
    }
  }
  let lulu = new Gfriend('v');
  console.log('构造函数和实例',lulu ); //  v
}

{
  // 类的继承
  class Gfriend{
    constructor(name='甜甜圈'){
      this.name=name;
    }
  }
  //  子类 继承 父类
  class Child extends Gfriend{

  }

  console.log('继承',new Child()); //  name: '甜甜圈'
}

{
  // 继承传递参数
  class Gfriend{
    constructor(name='甜甜圈'){
      this.name=name;
    }
  }

  class Child extends Gfriend{
    constructor(name='child'){
      super(name); 
   //  继承父类的构造函数参数列表 ,注意:super要放在构造函数的第一行
      this.type='child'; // this 放在super之后
    }
  }

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

{
  // getter,setter
  class Gfriend{
    constructor(name='甜甜圈'){
      this.name = name;
    }

    get longName(){ // 不是方法,是属性
      return 'mk'+this.name
    }

    set longName(value){  // 给这个属性赋值,会把值赋给当前的这个name
      this.name = value;
    }
  }

  let v = new Gfriend();
  console.log('getter',v.longName); // 甜甜圈
  v.longName='hello';
  console.log('setter',v.longName); // mkhello
}

{
  // 静态方法 用static修饰
  class Gfriend{
    constructor(name='甜甜圈'){
      this.name=name;
    }
    // 静态方法 ,通过类去调用,而不是通过类的实例去调用
    static tell(){
      console.log('tell');
    }
  }

  Gfriend.tell(); // tell

}

{
  // 静态属性
  class Gfriend{
    constructor(name = '甜甜圈'){
      this.name = name;
    }

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

  Gfriend.type='test';

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

}

 

你可能感兴趣的:(ES6 的类和对象的简单解析)