>>> function () {}
SyntaxError
>>> f = function() {}
f = function() {}
>>> new function() {}
>>> Object
>>> new Function()
function anonymous() {}
>>> Function()
function anonymous() {}
>>> f = (function() { a = 10; return function() {console.log(a);} })();
>>> f()
10
undefined
>>> f = (function() { a = 10; return new Function('console.log(a)'); })();
>>> f()
undefined
Thus, I have two questions:
-
Why is the
Functionconstructor returning a new function even without thenewoperator? -
Are functions created with the
Functionconstructors NOT closures?
Calling
Function()is the same as callingnew Function():Yes, the scope of the function is set to the global environment, not to the scope of the lexical environment. See http://es5.github.com/#x15.3.2.1, step 11:
That means using the
Functionconstructor is as if you declared a function in global scope, regarding the scope it can access (not regarding where the function is visible).This is different from using function declarations/expressions, where the scope is based on the current exectution context (http://es5.github.com/#x13):