子类遵循父类的结构

问题描述 投票:0回答:1

我有以下两个类:

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

    }
}

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

javascript node.js oop ecmascript-6 es6-class
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.