子班遵循父班的结构

时间:2019-03-23 14:48:16

标签: javascript node.js oop ecmascript-6 es6-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()) {

    }
}

是否有一种方法可以使它也适用于所有子类,而不必在每个子类中都执行相同的操作?

1 个答案:

答案 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()