Using eval method to get class from string in Firefox

六眼飞鱼酱① 提交于 2019-12-02 05:29:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!