Tra*_*ace 8 javascript ecmascript-6
在ES6中,我可以实现每个案例的块范围:
switch(somVar){
case 'first':
{
let itemId='foo';
}
break;
case 'second':
{
let itemId='bar';
}
}
Run Code Online (Sandbox Code Playgroud)
显然,itemId
不妨在最高层宣布.
对于我的用例,本地范围的变量更有意义,因为在我的整体代码中,它更容易识别正在发生的事情,并且存在许多case
,而一些块包含有问题的变量而其他块则没有.
我没有看到switch/case
用作常用的块作用域.
我的问题很简单,是否有理由不这样做,风格明智或其他.
编辑,更新示例代码以避免混淆:
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
}
}
Run Code Online (Sandbox Code Playgroud)
itemId可以在顶部声明,但我更愿意查看每个案例的属性.似乎没有直接的理由在不同的情况下共享变量.对于基本相同的东西来说,"发明"一个不同的名称似乎也是无稽之谈.
这可能以不同的方式编写,但此示例是Flux架构中的常见模式.
将逻辑抽象为函数。Switch 语句本身很难阅读,更不用说一堆逻辑和变量范围了。将逻辑抽象为函数要好得多。此外,在抽象为函数之后,您可能会注意到并没有太多需要 switch 语句。请参阅DockYard 风格指南的避免使用 switch 语句部分。
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意 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]();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2112 次 |
最近记录: |