ES6 中对于class类的理解之加深理解

149 阅读1分钟
class Parent {
  // 构造函数中的this指的是其本身
  constructor(name) {
    console.log(this, '构造函数中的this默认指向实例');
    this.name = name;
  }
  // 类可以调用静态方法,但是类的实例不可以
  static create() {
    // 注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。
    console.log(this.name); //Person
    return '我是父类的静态方法'
  }
  speak() {
    return this.name
  }
}
// 使用extends关键字,父类继承于子类
class Child extends Parent {
  constructor(name, age) {
    /* 
      1.super 关键字只能出现在子类constructor中  
      2.super 关键字用于this之前
      3.必须在子类的构造函数内调用super(),否则会报错
      4.super([arguements]) 用于访问父类的构造函数
      5.super.parentFunction([arguements])访问父类上的方法
      6.super([arguements])调用会生成一个空对象,
      作为context来调用父类的constructor,返回this对象,
      作为子类constructor的context继续调用构造函数。
      context:执行上下文 constructor:构造函数
    */
    super(name);
    /*相当于Parent.prototype.constructor.call(this,name)
    或者Parent.call(this.name) */
    this.age = age;
  }
  static create(name, age) {
    return new Child(name, age)
  }
  showAge() {
    return this.age;
  }
  showName() {
    return this.name;
  }
  showParentFn() {
    return super.speak()
    //相当于
    //return Parent.prototype.speak.call(this)
  }

}

let parent = new Parent("wgh");
let child = new Child("cym", 24)
Parent.create(); //我是父类的静态方法
parent.speak(); //wgh
child.showAge(); //24
child.showName(); //cym
child.showParentFn(); //cym
// 子类可以调用父类上的方法
child.speak(); //cym