Ben Aston
Ben Aston

Reputation: 55749

Should using the Function constructor form a closure?

Functions create a closure in JavaScript.

There are three ways of defining functions in JavaScript: function statement, function expression (named/unnamed) and using the Function constructor function.

Should using the Function constructor form a closure?

Upvotes: 0

Views: 48

Answers (1)

Amit Joki
Amit Joki

Reputation: 59252

No. They are always in global context, and are able to access their own variables and obviously the global ones.

MDN: (Emphasis mine)

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.

Upvotes: 1

Related Questions