我在Github上看到过这样的代码:
switch (type) {
case 'case1':
return this.case1();
case 'case2':
return this.case2();
case 'case3':
return this.case3();
...
default:
return this.default();
}
它包含25个案例+默认案例。
我会使用不同的方式,并将所有功能打包到一个对象中:
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();
}
您还可以动态添加更多案例:
if(optionEnabled) {
list.case4 = function() {
return /* code */;
};
list.case5 = list.case6 = function() {
return /* code */;
};
}
嗯,它可以更漂亮一点。我的问题是:如果你有大量的病例,而且它们仍然可以扩大,哪种方法更好?
重要因素包括:
- 性能
- 可扩展性(以我的方式,它更容易扩展,我的代码只包含单词
case1
、case2
、case3
,每个单词一次) - 可读性和可理解性
在第二个示例中,您以内联方式定义函数。因此,您只能看到单词case1
、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 */;
}();
}
顺便说一句,当你必须在运行时设置你的"案例"时,你必须将你的函数设置到一个对象中。
更新
代码更正,感谢@Artisan72的评论。