gpt4 book ai didi

javascript - 子类遵循父类的结构

转载 作者:行者123 更新时间:2023-12-02 23:57:20 26 4
gpt4 key购买 nike

我有以下两个类(class):

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()) {

}
}

有没有办法让它也适用于所有子类,而不必在每个子类中都做同样的事情?

最佳答案

您可以添加另一个方法,如果 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()

关于javascript - 子类遵循父类的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55314948/

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