问题
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?
回答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());
回答2:
I tried another method that works just as using parentheses and parentheses seems much simpler as it doesn't pollute global names.
result = eval(`(class a{})`)
console.log(result)
result = eval(`class a{} window.a=a`)
console.log(result)
来源:https://stackoverflow.com/questions/39298985/using-eval-method-to-get-class-from-string-in-firefox