最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return value after eval - Stack Overflow

programmeradmin4浏览0评论
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?

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?

Share Improve this question asked Mar 6, 2011 at 13:59 Max FraiMax Frai 64.4k81 gold badges204 silver badges311 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论