在 ES6 中,我可以实现每个案例的 block 作用域:
switch(somVar){
case 'first':
{
let itemId='foo';
}
break;
case 'second':
{
let itemId='bar';
}
}
显然,itemId
也可以在顶部声明。
对于我的用例,局部范围的变量更有意义,因为在我的整体代码中,更容易识别正在发生的事情,并且有许多 case
,而一些 block 包含有问题的变量而其他人则没有。
我还没有看到用于 switch/case
的 block 作用域作为常见用法。
我的问题很简单,是否有理由不这样做,无论是风格上还是其他方面。
编辑、更新示例代码以避免混淆:
const someFunc(action) => {
switch(action.type){
case 'first':
{
let itemId=action.someObj.someProp.id;
//Do something with itemId
}
break;
case 'second':
{
let itemId=action.someObj.someProp.id;
//Do something with itemId
}
break;
case 'third':
//No use of itemId
}
}
itemId 可以在顶部声明,但我更愿意查看每个案例的属性。似乎没有立即理由在不同情况下共享变量。为本质上相同的东西“发明”不同的名称似乎也是无稽之谈。
这可能有不同的写法,但这个例子是 Flux 架构中的常见模式。
最佳答案
将逻辑抽象为函数。 switch 语句本身很难阅读,更不用说一堆逻辑和变量作用域了。将逻辑抽象为函数要好得多。此外,在抽象为函数之后,您可能会注意到并没有太多需要一起使用 switch 语句。参见 Avoid use of switch statements DockYard 风格指南的一部分。
function handleFirstCase() {
var itemId = 'foo';
// Do stuff with itemId
return expectedValue;
}
function handleSecondCase() {
var itemId = 'bar';
// Do stuff with itemId
return expectedValue;
}
let result;
switch(somVar){
case 'first':
result = handleFirstCase();
break;
case 'second':
result = handleSecondCase();
break;
}
注意 switch 语句是如何变成一行的。这可以很容易地提炼为字典查找:
const CASES = {
first() {
var itemId = 'foo';
// Do stuff with itemId
return expectedValue;
},
second() {
var itemId = 'bar';
// Do stuff with itemId
return expectedValue;
}
};
let result = CASES[someVar]();
关于javascript - 带有 in 开关的 ES6 block 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38828898/