gpt4 book ai didi

class - 使用JavaScript ES6/ES2015子类化时如何覆盖继承的方法

转载 作者:行者123 更新时间:2023-12-03 11:09:36 28 4
gpt4 key购买 nike

我创建了一个扩展Array的类。我想在调用继承的push函数之前执行任意代码。

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

关于class - 使用JavaScript ES6/ES2015子类化时如何覆盖继承的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39886830/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com