What I tried (which works in chrome)
var class_str = "class Test {};";
var a = eval(class_str);
console.log(new a());
Raises following error in Firefox 46:
TypeError: a is not a constructor
a
is undefined and using new A()
returns ReferenceError: A is not defined
.
What is different on Firefox?
What I tried (which works in chrome)
var class_str = "class Test {};";
var a = eval(class_str);
console.log(new a());
Raises following error in Firefox 46:
TypeError: a is not a constructor
a
is undefined and using new A()
returns ReferenceError: A is not defined
.
What is different on Firefox?
Share Improve this question asked Sep 2, 2016 at 18:49 previous_developerprevious_developer 11k7 gold badges44 silver badges67 bronze badges 5-
just what is returned from eval. try
var class_str = "class Test {}; return Test;";
– Daniel A. White Commented Sep 2, 2016 at 18:53 -
It returns
SyntaxError: return not in function
@DanielA.White Chrome does not work that way, too. – previous_developer Commented Sep 2, 2016 at 18:56 -
If you type
class Test {};
into the console, you'll see that Firefox gives youundefined
, while Chrome gives you the class. So Chrome is providing a value for the last statement in the program, while Firefox isn't. Not sure which is correct. Another example of a statement returning a value would be to see the result of afor
statement usingeval
.var x = eval("for (var i = 0; i < 10; i++) { i }"); console.log(x); // 9
– user1106925 Commented Sep 2, 2016 at 18:57 -
@squint Thanks, it turns out I just need to put the whole class in parentheses, as in
(class Test {})
– previous_developer Commented Sep 2, 2016 at 19:09 - Possible duplicate of Using eval to execute functions or How to convert text to a function using JavaScript – Oriol Commented Sep 2, 2016 at 19:36
2 Answers
Reset to default 14Putting the whole class string in parentheses works.
Fixed code:
var class_str = "(class Test {})";
var a = eval(class_str);
console.log(new a());
I tried another method that works just as using parentheses and seems much simpler as it doesn't pollute global names.
result = eval(`class a{} window.a=a`)
console.log(result)