简体   繁体   中英

How to define this in a constructor function

 var a = 'global'; var b = function() { var a = 'scoped'; new Function('console.log(a)')(); } b(); 

Code above will log 'global' , what should I do to log 'scoped' instead?

From MDN :

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues to eval. However, unlike eval, the Function constructor creates functions which execute in the global scope only.

Since your problem is about trying to access a variable that isn't in the global scope: You can't.

Look for a solution to the underlying problem that doesn't involve new Function .

To quote from the Function docs :

However, unlike eval , the Function constructor creates functions which execute in the global scope only.

  eval("console.log(a)");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM