JS / node.js:大型开关块与function集合
我在Github上看到了这样的代码:
switch (type) { case 'case1': return this.case1(); case 'case2': return this.case2(); case 'case3': return this.case3(); ... default: return this.default(); }
它包含25个案例+默认情况。
我会用不同的方式把所有的function打包到一个对象中:
var list = {}; list.case1 = function() { return /* code */; }; list.case2 = function() { return /* code */; }; list.case3 = function() { return /* code */; }; // and so on if(type in list) { return list[type](); } else { return this.default(); }
您也可以dynamic添加更多的案例:
if(optionEnabled) { list.case4 = function() { return /* code */; }; list.case5 = list.case6 = function() { return /* code */; }; }
那么,它可以有点漂亮。 我的问题是:如果有大量的案例,哪个方法更好,他们仍然可以扩大?
重要的因素是:
- 性能
- 可扩展性(以我的方式扩展更容易,我的代码每个只包含
case2
,case3
,case3
一次) - 可读性和可理解性
在第二个例子中,你可以定义你的函数内联。 因此,你会看到单词case2
, case2
等。 但是您可以使用switch/case
实现相同的结果来定义内联函数:
switch (type) { case 'case1': return function() { return /* code */; }(); case 'case2': return function() { return /* code */; }(); case 'case3': return function() { return /* code */; }(); ... default: return function() { return /* code */; }(); }
顺便说一句,当你必须在运行时设置你的“案例”,你必须将你的function设置为一个对象。
更新
代码更正,谢谢@ Artisan72的评论。