Function declarations in statements

Brendan Eich brendan at mozilla.org
Sat Mar 17 21:55:19 PDT 2007


On Mar 17, 2007, at 8:11 PM, Igor Bukanov wrote:

> No, the translated code is:
> var odd = function (n) { return n == 0 ? false : even(n-1); }
> var even = function (n) { return n == 0 ? true : odd(n-1); }
> alert(odd(4));
>
> since the idea for "function f() {}" at any place in the block to mean
> "var f = function f() {}" at the beginning of the block. For top-level
> function statements this is exactly what is ES3 requires,

It's still different, according to ECMA-262 10.1.3, second bulleted  
item vs. third -- note how var does not create a new property if one  
already exists:

• For each FunctionDeclaration in the code, in source text order,  
create a property of the variable object whose
name is the Identifier in the FunctionDeclaration, whose value is the  
result returned by creating a Function object
as described in section 13, and whose attributes are determined by  
the type of code. If the variable object
already has a property with this name, replace its value and  
attributes. Semantically, this step must follow the
creation of FormalParameterList properties.

• For each VariableDeclaration or VariableDeclarationNoIn in the  
code, create a property of the variable object
whose name is the Identifier in the VariableDeclaration or  
VariableDeclarationNoIn, whose value is undefined
and whose attributes are determined by the type of code. If there is  
already a property of the variable object with
the name of a declared variable, the value of the property and its  
attributes are not changed. Semantically, this
step must follow the creation of the FormalParameterList and  
FunctionDeclaration properties. In particular, if a
declared variable has the same name as a declared function or formal  
parameter, the variable declaration does
not disturb the existing property.

Backward compatibility is required here, since script on the web  
declares functions with names that replace pre-defined properties  
that may not have the right default attributes (in particular, may be  
ReadOnly and DontDelete).

> but it also
> makes a consistent rules for functions declared inside blocks.

This part, I agree is an improvement on the function statement rule  
in SpiderMonkey and Rhino. ES4 already has |let function f(...)...|  
for lexically scoped block-local function binding (hoisted to top of  
block). It sounds like your proposal is the same as let function  
provided the function statement is enclosed in a block. With let, a  
binding such as

   if (cond) let x = 42;

binds x in the enclosing block, not in an implicit block around the  
if's then clause.

/be
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.mozilla.org/pipermail/es-discuss/attachments/20070317/72ca0e42/attachment-0002.html 


More information about the Es4-discuss mailing list