Skip to content

Instantly share code, notes, and snippets.

@redgeoff
Last active December 29, 2020 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redgeoff/62739d7ae1929941d224966081468b59 to your computer and use it in GitHub Desktop.
Save redgeoff/62739d7ae1929941d224966081468b59 to your computer and use it in GitHub Desktop.
JavaScript New Function Only Has Access to Global Scope
// 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