想象一个任务,其中有一组具有 type
属性的资源。基于此 type
需要执行不同的功能。实现这一点的一种方法是通过多个 if/else 或 switch/case 条件。
// at run time (run many times)
if (resources[ix].type == 'TYPE_ONE') {
runFuctionOne();
}
else{
runFuctionTwo();
}
另一种方法是再维护一个属性,如execute
,它会被分配一个满足资源类型
的函数。那么你就不需要 if/else 条件,可以直接执行它的功能,比如:
// at assign time (run once)
if (resources[ix].type == 'TYPE_ONE') {
resources[ix].execute = runFunctionOne;
}
else{
resources[ix].execute = runFuctionTwo;
}
// then at run time (run many times)
resources[ix].execute();
那么,哪种方式效率更高?有没有更好的方法?
编辑:我对在 Node.js 环境而非浏览器环境中高效的解决方案更感兴趣。
最佳答案
我认为函数映射在这里是更好的选择。
定义全局 map
var fns = {
'TYPE_ONE' : runFunctionOne,
'TYPE_TWO' : runFunctionTwo
};
然后使用它
var fn = fns[resources[ix].type];
if (typeof fn == 'function') {
fn()
}
或者使用switch
var fn;
switch (resources[ix].type) {
case "TYPE_ONE" :
fn = runFunctionOne;
break;
case '' :
// execute code block 2
break;
default :
//
}
fn()
关于javascript - 哪个维护: JavaScript function references or Boolean + IF conditions?效率更高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15756718/