简体   繁体   English

解决动态函数调用的范式/模式

[英]paradigm / pattern to solve dynamical function calling

I've been puzzling the last few days on trying to solve a problem in Javascript (typescript), and I'm unable to come to a solution that I feel comfortable with. 最近几天,我一直在困惑地尝试解决Javascript(打字稿)中的问题,但我无法找到自己满意的解决方案。 So here is my scenario: 所以这是我的情况:

You have a class, that has a public function.. this public function will be called many thousands of times so performance is paramount. 您有一个具有公共功能的类。此公共功能将被调用数千次,因此性能至关重要。 However, that function must be able to perform a dynamic task without the use of if statements or switching. 但是,该函数必须能够执行动态任务,而无需使用if语句或切换。 For an example... 举个例子...

class foo {
    constructor() {

    }

    doWork1() {
        return 1 + 1;
    }

    doWork2() {
        return 5 + 5;
    }
}

Now any class MUST be able to call an agnostic doWork function, but without knowing if it should call doWork1, or doWork2. 现在,任何类都必须能够调用不可知的doWork函数,但不知道是否应调用doWork1或doWork2。 I have looked into mapping the functions to an enumerable, however performance tests show that to be a horrible approach, though it is scalable. 我已经研究过将功能映射到可枚举的对象,但是性能测试表明这是一种可怕的方法,尽管它具有可伸缩性。

Therefore, the best solution I have come up with to date is thus: 因此,迄今为止我提出的最佳解决方案是:

class foo {

    public doWork:Function;

    constructor(fnFlag) {
        if(fnFlag === 1) {
            this.doWork = this.doWork1;
        } else if (fnFlag === 2) {
            this.doWork = this.doWork2;
        }
    }

    doWork1() {
        return 1 + 1;
    }

    doWork2() {
        return 5 + 5;
    }
}

In the code above, the public function doWork can be called by any class and will always point to the function it is initialised with. 在上面的代码中,公共函数doWork可以由任何类调用,并且始终指向初始化该函数的函数。 However, something just isn't sitting right with me and I don't feel like this is the best approach. 但是,有些事情并不适合我,我不认为这是最好的方法。 I was contemplating passing the function in the constructor and assigning it there? 我正在考虑在构造函数中传递函数并在那里分配它?

Any thoughts or advice on a pattern to solve an issue such as this would be most appreciated. 对于解决此类问题的模式的任何想法或建议,将不胜感激。 Thanks. 谢谢。

If you can pass the name of the function you want to call instead of an enum you can write it like this: 如果可以传递要调用的函数的名称而不是枚举,则可以这样编写:

constructor(functionName) {
    this.doWork = this[functionName];
}

You can verify this with TypeScript playground . 您可以使用TypeScript Playground对此进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM