如何返回eval(code)并使用JavaScript返回对象? [英] How do I return eval(code) and get an object back with JavaScript?
本文介绍了如何返回eval(code)并使用JavaScript返回对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码。我要它执行的是加载一个.js文件,然后运行它。它运行后,我希望它返回一个参数甚至是一个对象。
I have this bit of code. What I want it to do is is load a .js file and then run it. wWen it runs I want it to return a parameter or even better an object.
这是我页面中的代码
var runCode = function(){
var xhr=new XMLHttpRequest();
xhr.open('GET','io.js',false);
xhr.send();
return eval(xhr.responseText);
};
这是is.js
var IO = new function(){
this.run = true;
return 'io';
};
return IO
但是当我运行它时,我得到 Uncaught SyntaxError:Illegal return statement在控制台中。
But when I run it i get "Uncaught SyntaxError: Illegal return statement" in the console.
推荐答案
我发现的另一个解决方案是将字符串封装为 eval
放在函数内部,这非常简单。
Another solution I found is to encapsulate your string to be eval
'd inside a function, which is quite simple.
return eval("(function() {" + xhr.responseText + "})();");
这篇关于如何返回eval(code)并使用JavaScript返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文