How to return eval (code) and return an object using JavaScript?

I have this bit of code. I want it to download the .js file and then run it. wWen it starts, I want it to return a parameter or even a better object.

This is the code on my page

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

And this is.js

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

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

+3
source share
4 answers

Another solution I found is to encapsulate your string in eval'd inside a function, which is pretty simple.

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

. eval, -

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

The problem is that you cannot return beyond the function limits. You will need return IO;from your function runCodeafter completing the request.

0
source

Delete statement new

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

Source: https://habr.com/ru/post/1768749/


All Articles