最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using eval method to get class from string in Firefox - Stack Overflow

programmeradmin5浏览0评论

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 you undefined, 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 a for statement using eval. 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
Add a ment  | 

2 Answers 2

Reset to default 14

Putting 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)
发布评论

评论列表(0)

  1. 暂无评论