我有以下两个课程:
class AcceptCommand extends Command {
init(client, db) {
super.init(client, db);
}
async hasPermission() {
}
async run() {
if (this.hasPermission()) {
}
}
}
和
export class Command {
init(client, db) {
this.client = client;
this.db = db;
}
setTrigger(trigger) {
this.trigger = trigger;
}
getTrigger() {
return this.trigger;
}
async hasPermission() {
}
async run() {
if (this.hasPermission()) {
}
}
}
我希望在运行run()函数时首先检查用户是否具有权限(this.hasPermission()
)。
在父类Command
中,我这样做:
async hasPermission() {
}
async run() {
if (this.hasPermission()) {
}
}
是否有一种方法可以使它也适用于所有子类,而不必在每个子类中都执行相同的操作?
答案 0 :(得分:1)
如果hasPermission
返回true,则可以添加另一个将执行的方法。并在子类中重写此函数。像这样:
class Command {
actionIfHasPermission () {
console.log('Command actionIfHasPermission')
}
async hasPermission() {
console.log('Command hasPermission')
return false
}
async run() {
if (this.hasPermission()) {
this.actionIfHasPermission()
}
}
}
class AcceptCommand extends Command {
actionIfHasPermission() {
console.log('AcceptCommand actionIfHasPermission')
}
async hasPermission() {
console.log('AcceptCommand hasPermission')
return true
}
}
const instance = new AcceptCommand()
instance.run()