Last active
December 29, 2020 22:01
-
-
Save redgeoff/62739d7ae1929941d224966081468b59 to your computer and use it in GitHub Desktop.
JavaScript New Function Only Has Access to Global Scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The following code proves that functions created in `new Function()` cannot access local scope | |
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function for more details | |
let userDefinedFunction = function () { | |
const foo = 'bar'; | |
const fn = () => { console.log(foo) }; | |
fn(); // This succeeds and prints 'bar' | |
return new Function('props', `const f = ${fn.toString()}; return f(props);`) | |
} | |
let fun = userDefinedFunction(); | |
fun(); // Fails as new Function cannot access foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment