我有以下两个类:
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()