Strange interaction between new function and eval

Is there a reason why this line of code does not work?

new Function("eval('function foo(){ alert() }'); foo()")() 

It displays a warning in Chromium as expected, but does not work in Firefox (foo is undefined). Is this a Firefox bug, or is there something wrong with my code?

+5
source share
1 answer

The problem is that eval does not inherit the global scope, so foo is created in a different scope than where it is called. You can solve this problem by specifying the scope explicitly, either in the function definition, or by going to eval . That is, both of the following snippets work as expected:

 new Function("eval('window.foo = function(){ alert() }'); foo()")() new Function("eval('function foo(){ alert() }', this); foo()")() 

This behavior seems to be related to strict mode, as explained by the answer "use strict" here; + jQuery.getScript () = script cannot export to the global namespace .

-1
source

All Articles