当前位置: 代码迷 >> 综合 >> super 是什么?
  详细解决方案

super 是什么?

热度:11   发布时间:2024-02-19 22:54:02.0

1. 先来一个题外话

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

constructor 中的 this 指向的是类的实例

2. 在 es6 类的继承中,当子类 extends 父类的时候,需要 super(),并且必须在 this 使用之前 调用 super()

在构造函数中使用时,super关键字将单独出现,并且必须在使用this关键字之前使用。

super关键字也可以用来调用父对象上的函数(主要功能,与父类传递信息)

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())

 

  相关解决方案