views:

54

answers:

3

I have this bit of code. What I want it to do is is load a .js file and then run it. when 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.

A: 

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.

Delan Azabani
A: 

Remove the new statement

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

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};')
Gaurav Saxena
Couldn't you just use `IO;` as the final statement? Braces aren't that necessary.
Delan Azabani
yeah, using just IO works too. I was trying to write it as an object to make eval return it
Gaurav Saxena