1

typeプロパティを持つリソースの配列があるタスクを想像してください。これに基づいて、typeさまざまな機能を実行する必要があります。これを実装する 1 つの方法は、複数の if/else または switch/case 条件を使用することです。

// at run time (run many times)
if (resources[ix].type == 'TYPE_ONE') {
    runFuctionOne();
}
else{
    runFuctionTwo();
}

もう 1 つの方法はexecute、リソースのtype. 次に、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環境で効率的なソリューションに興味があります。

4

1 に答える 1

2

I think a function map will be a better option here.

Define a global map

var fns = {
    'TYPE_ONE' : runFunctionOne,
    'TYPE_TWO' : runFunctionTwo
};

Then use it

var fn = fns[resources[ix].type];
if (typeof fn == 'function') {
    fn()
}

Or use switch

var fn;
switch (resources[ix].type) {
    case "TYPE_ONE" :
        fn = runFunctionOne;
        break;
    case '' :
        // execute code block 2
        break;
    default :
        //
}

fn()
于 2013-04-02T05:27:08.717 に答える