简体   繁体   English

JavaScript中两组功能如何切换

[英]How to switch between two sets of functions in JavaScript

I want to make parts of a Cypress test suite run a set of functions based on a configuration variable.我想让赛普拉斯测试套件的一部分运行基于配置变量的一组函数。 Ie version 1 of the function showMessage should be used if the version variable is 1, and version 2 if the version variable is 2. I can do it with if statements like demonstrated below.即,如果版本变量为 1,则应使用 function showMessage 的版本 1,如果版本变量为 2,则应使用版本 2。我可以使用如下所示的 if 语句来做到这一点。 I am a JavaScript noob, but I know there are more elegant ways of doing it.我是 JavaScript 菜鸟,但我知道有更优雅的方法可以做到这一点。

function showMessage(version) {
    if (version == '1') {
        console.log('Version 1');
    }
    else {
        console.log('Version 2')
    }
}

showMessage('2');

I would ideally like to have the functions in separate folders, each defining their own version of showMessage (without the if statement), but I am not sure how to do it properly in JavaScript.理想情况下,我希望将函数放在单独的文件夹中,每个文件夹都定义自己的 showMessage 版本(没有 if 语句),但我不确定如何在 JavaScript 中正确执行此操作。

In a way, I'm asking for an extremely lightweight dependency injection mechanism.在某种程度上,我要求一种极其轻量级的依赖注入机制。

There is many many ways to do that.有很多方法可以做到这一点。 It is basically a decision of what is less work and is the most readable.它基本上是决定什么是更少的工作并且是最易读的。 But at the end there is never a way around for selecting what you want.但最终没有办法选择你想要的东西。 A different approach to if in each function would be:如果在每个 function 中,不同的方法是:

 var a = {}; var b = {}; a.showMessage = () => { console.log('Version 1'); } b.showMessage = () => { console.log('Version 2'); } version ='1' //set up 'reference' object c in one place, based on the selected version c = (version == '1'? a: b); //Then every time we call showMessage, use the reference object (no ifs) c.showMessage();

Another option would be to use the prototype of a function.另一种选择是使用 function 的原型。 That is to be said, literally the same as the above example but with the fact that it is more reuseable in some kind of way.也就是说,字面上与上面的示例相同,但事实上它以某种方式更可重用。

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

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