'Using eval method to get class from string in 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?



Solution 1:[1]

Putting the whole class string in parentheses works.

Fixed code:

var class_str = "(class Test {})";
var a = eval(class_str);
console.log(new a());

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 previous_developer
Solution 2 IT goldman