如何使用 JavaScript 返回 eval(code) 并获取对象?

发布于 2024-09-26 22:16:27 字数 432 浏览 0 评论 0原文

我有这段代码。我想要它做的是加载 .js 文件然后运行它。当它运行时,我希望它返回一个参数,甚至更好的是一个对象。

这是我页面中的代码

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:非法返回语句”。

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.

This is the code in my page

var runCode = function(){
    var xhr=new XMLHttpRequest();
    xhr.open('GET','io.js',false);
    xhr.send();
    return eval(xhr.responseText);
};

And this is the is.js

var IO = new function(){
    this.run = true;
    return 'io';
};
return IO

But when I run it i get "Uncaught SyntaxError: Illegal return statement" in the console.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

羅雙樹 2024-10-03 22:16:27

我发现的另一个解决方案是将要进行评估的字符串封装在函数内,这非常简单。

return eval("(function() {" + xhr.responseText + "})();");

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 + "})();");
魔法少女 2024-10-03 22:16:27

不能在函数外部使用 return。但要从 eval 返回值,您可以使用以下语法 -

eval('var IO = function(){this.run = true; return "io";};{IO};')

You cannot use return outside of a function. But to return a value from eval you can use the following syntax-

eval('var IO = function(){this.run = true; return "io";};{IO};')
笑着哭最痛 2024-10-03 22:16:27

问题是,你不能在函数之外返回。您需要在请求完成后从 runCode 函数返回 IO;。

Problem is, you can't return outside of a function. What you'll need to is to return IO; from your runCode function after the request completes.

时光匆匆的小流年 2024-10-03 22:16:27

删除 new 语句

var IO = function(){ 
    this.run = true; 
    return 'io'; 
}; 
return IO 

Remove the new statement

var IO = function(){ 
    this.run = true; 
    return 'io'; 
}; 
return IO 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文