ES6 的类和对象的简单解析

148 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

ES6 的类和对象的简单解析

在ES6中增加了类的概念,可以使用class关键字声明一个类,之后以这个类来实例化对象。 类抽象了对象的公共部分,它泛指某一大类。 对象特指某一个,通过类实例化一个具体的对象。  

{
  // 一个类的基本定义和生成实例
  // 定义一个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

}