Class - inheritance
Inheritance allows subclasses to get the parent class (base class), the property can be expanded, adding new methods and properties, etc.
extends
class P {
constructor(name,age) {
this.name = name
this.age = age
}
say () {
console.log(this.name)
}
}
class L extends P {
constructor(name,age,sex,hobby) {
super(name,age)
this.sex = sex
this.hobby = hobby
}
say() {
console.log(`${this.name} + ${this.hobby}`)
}
}
let p = new P ("xiaoming",32)
p.say() //xiaoming
let l = new L("kangkang",23,"man","唱歌")
l.say() //kangkang + 唱歌
It will be subject to a subclass of a subclass of the parent class and method of the same name.
super()
effect
As a parent class constructor calls
After calling subclass you can get the properties and methods of the parent class (to be on call at the beginning) (subclass of this in the constructor of the parent class to run again)
Calls as a way to target
Non-static method to access super -> parent class prototype
Access super in a static method -> parent
When calling super, the parent class operation this is always this subclass
class L extends P {
constructor(name,age,sex,hobby) {
super(name,age)
this.sex = sex
this.hobby = hobby
}
say() {
console.log(`${this.name} + ${this.hobby}`)
}
}
Polymorphism
The same interface, do different things in different situations (same interfaces, different manifestations)
class L extends P {
constructor(name,age,sex,hobby) {
super(name,age)
this.sex = sex
this.hobby = hobby
}
say() {
super.say() // 同一函数名不同结果
console.log(`${this.name} + ${this.hobby}`)
}
}
Overload
Different function parameters, different operations
ES5 class inheritance to achieve
function P() {
this.name = "kangang"
this.gender = 2
this.say = function () {
console.log("我是父类的哦!")
}
}
P.prototype.test = function() {
console.log(`我是原型上的test方法!!!`)
}
function C() {
P.call(this)
this.name = "xiaojun"
this.age = 21
}
var child = new C()
child.say() //我是父类的哦!
child.test() // child.test is not a function
// 上面的解决方法是
C.prototype = new P()