1

I like the concept of "jump dictionaries" that contain key:values, where the values are functions. I'm not sure if I should like this concept or not, though.

I want to replace a long list if if-else if statements. (Should I use switch statements?)

Is there a way to implement a "jump dictionary" without using eval? (I already read this about why eval is bad: Why is using the JavaScript eval function a bad idea? )

Example using eval

function some_func(arg) { console.log('I am a some func') };
function find_my(arg) { console.log('we are looing for your ' + arg); };

var jump = {
    '1' : 'some_func()',
    '2' : 'find_my("cat")',
    '3' : 'find_my("dog")'
}

eval(jump['3'])
eval(jump['2'])
eval(jump['1'])

Thanks.

Community
  • 1
  • 1
cathy.sasaki
  • 3,995
  • 6
  • 28
  • 39

1 Answers1

6

Use anonymous functions:

var jump = {
    "1":some_func,
    "2":function() {find_my("cat");},
    "3":function() {find_my("dog");}
}

Now you can call:

jump["3"]();
jump["2"]();
jump["1"]();
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592