【问题标题】:Child class follow structure of parent class子类遵循父类的结构
【发布时间】:2019-08-14 08:17:23
【问题描述】:

我有以下两个类:

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

    }
}

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

【问题讨论】:

  • 请注意,鉴于hasPermissionasync 方法,您将要使用if (await this.hasPermission())

标签: javascript node.js oop ecmascript-6 es6-class


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 2013-04-26
    相关资源
    最近更新 更多