1
function someFunc() { return 'Hello, world'; }
function call(funcName) { eval(funcName + '()'); }

console.log(call('someFunc'));

But console.log doesn't print 'Hello world'. How can I return value after eval function?

Max Frai
  • 61,946
  • 78
  • 197
  • 306

3 Answers3

4

You want:

call(funcName) { window[funcName](); }

And don't use the void keyword. It ignores return values and always returns undefined from a statement.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • I'm not too sure about this, but if eval works in with clousures (like functions in functions etc), than that code won't work. – Alxandr Mar 06 '11 at 14:06
  • @Alxandr depends where the call function is defined. Depends where `someFunc` is defined. It's bad to rely on that. You really want to store functions on an object and call them by string key on the object. – Raynos Mar 06 '11 at 14:07
  • @Raynos how about something like `(this[fnName] || window[fnName])()`? – Alxandr Mar 06 '11 at 14:11
  • However, what if I did `function a() { var b = function() {/*do something*/}; call('b'); }` (silly example, yes I know). Not that it has anything to do with OP, but I'm just curious :-P – Alxandr Mar 06 '11 at 14:12
  • @Alxandr `b` is defined as a local variable on the stack. It is not accesible in `this` not in the global scope (`window`). `b`lives in the CallObject. [You can't programmatically access it](http://stackoverflow.com/questions/3831932/access-all-local-variables) – Raynos Mar 06 '11 at 14:18
  • @Raynos what would `eval('b')` yield when called inside a then? I've tried this in FF now, and it gives me the function b, thought it might differ between browsers. So, how about something like `function call(name) { var f = eval(name); if(typeof name == 'function') { f(); }}`. Then you just need to do some sort of regex to check that name isn't malicious js. A bit overkill maybe, but that use of eval I wouldn't call evil, no? – Alxandr Mar 06 '11 at 14:22
  • @Alxandr alternatively don't write shit generic code that requires the use of `eval`. Sorry but eval should be avoided for most cases. It's uses are very limited. – Raynos Mar 06 '11 at 15:06
1

To answer your question using eval :

function someFunc() { return 'Hello, world'; }

function call(funcName) { return eval(funcName + '()'); }

console.log(call('someFunc'));

And you can use eval if you trust the input. this is the rule of thumb

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

Don't use eval -- it's evil. Why don't you try this:

Get JavaScript function-object from its name as a string?

After getting a reference to the function, you can simply call it and use the return value directly.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806