What is super?

1. Let me start with a digression

class Parent {
  constructor (name) {
    console.log('this', this) // person1
    this.name = name
  }
  getName () {
    return this.name
  }
}

let person1 = new Parent('zs')

This in the constructor points to an instance of the class

2. In es6 class inheritance, when the subclass extends the parent class, super() is required, and super() must be called before this is used

When used in the constructor, the superkeyword will appear alone and must be used thisbefore the keyword is used.

superKeywords can also be used to call functions on the parent object (main function, to pass information with the parent)

class Parent {
  // 父类需要接受name变量,但是实例化的时候,创建 Child 的实例,所以需要给父类传参数
  constructor (name) {
    this.name = name
  }
  getName () {
    return this.name
  }
}

class Child extends Parent {
  constructor (name, age) {
    super(name) // 1. 给父类传值, 父类需要接受name 2. 实例可以调用父类的函数
    this.age = age
  }
  getInfo () {
    return `${this.name},${this.age}`
  }
}
let child = new Child('zs', 23)
console.log(child.getInfo())
console.log(child.getName())

 

Guess you like

Origin blog.csdn.net/Luckyzhoufangbing/article/details/108654316