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
super
keyword will appear alone and must be usedthis
before the keyword is used.
super
Keywords 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())