使用 JavaScript ES6/ES2015 子类化时如何覆盖继承的方法
How do I override inherited methods when using JavaScript ES6/ES2015 subclassing
我创建了一个扩展 Array 的 class。我想在调用继承的推送函数之前执行任意代码。
class newArray extends Array{
//execute any logic require before pushing value onto array
this.push(value)
}
我找到的解决方案是在子类中创建一个与继承函数同名的新函数。在这种情况下推。然后在重写函数中通过 super 关键字调用继承函数。
class newArray extends Array{
push(value) {
//execute any logic require before pushing value onto array
console.log(`pushed ${value} on to array`)
super.push(value)
}
}
var array = new newArray
array.push('new Value')
我创建了一个扩展 Array 的 class。我想在调用继承的推送函数之前执行任意代码。
class newArray extends Array{
//execute any logic require before pushing value onto array
this.push(value)
}
我找到的解决方案是在子类中创建一个与继承函数同名的新函数。在这种情况下推。然后在重写函数中通过 super 关键字调用继承函数。
class newArray extends Array{
push(value) {
//execute any logic require before pushing value onto array
console.log(`pushed ${value} on to array`)
super.push(value)
}
}
var array = new newArray
array.push('new Value')