treecoder
treecoder

Reputation: 45091

JavaScript Internals 101: function and Function

>>> 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:

  1. Why is the Function constructor returning a new function even without the new operator?

  2. Are functions created with the Function constructors NOT closures?

Upvotes: 0

Views: 300

Answers (3)

Douglas
Douglas

Reputation: 37761

1, functions can return objects, so it isn't absurd that Function() returns one. I'd double check the docs if you want to use it, because it is unusual enough that it might not work in all browsers.

2, correct.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816384

Why is the Function constructor returning a new function even without the new operator?

Calling Function() is the same as calling new Function():

When Function is called as a function rather than as a constructor, it creates and initialises a new Function object. Thus the function call Function(…) is equivalent to the object creation expression new Function(…) with the same arguments.


Are functions created with the Function constructors NOT closures?

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:

11. Return a new Function object created as specified in 13.2 passing P as the FormalParameterList and body as the FunctionBody. Pass in the Global Environment as the Scope parameter and strict as the Strict flag.

That means using the Function constructor 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):

  1. Let funcEnv be the result of calling NewDeclarativeEnvironment passing the running execution context’s Lexical Environment as the argument

Upvotes: 7

didierc
didierc

Reputation: 14730

Function is the object used to implement functions, they are semantically the same underlying object.

However, a function is parsed at the same time as the script they belong to, whereas a Function body is parsed at instantiation time, which may explain why you get a difference of behaviour from your js interpreter.

see there for more information.

Upvotes: 1

Related Questions