0

Usually, a function remembers where it was born in the special property. It references the Lexical Environment from where it’s created.

But when a function is created using new Function, I am getting an error

My code:

function fun() {
  let x = 12;

  let y = new Function('console.log(x)');

  return y;
}

fun()(); // error: x is not defined

Does new Function does not support the closure concept of javascript Or Did I mess something wrong?

Thanks in advance

Orion
  • 248
  • 3
  • 10
  • 1
    Does this answer your question? [Are eval() and new Function() the same thing?](https://stackoverflow.com/questions/4599857/are-eval-and-new-function-the-same-thing) – CherryDT May 26 '21 at 07:16
  • `new Function` doesn't allow access to the surrounding scope, while `eval` does (as long as it's invoked directly). I'd say `eval` is the oddball here though, not `new Function` because it is unusual that passing a string to some function magically allows dynamic access to the current execution context's local scope variables... there is no way to recreate this behavior yourself. – CherryDT May 26 '21 at 07:19

0 Answers0