views:

36

answers:

2

In order to implement a tiny compiler that emits ECMAScript I need to know how strong a function object expression binds, i.e. what is the precedence of the "operator" function(a1, a2, ...) { ... }?

For example, how is function(a1, a2, ...) { ... } (b1, b2, ...) supposed to be parsed? To get the wished for result, namely the application of b1, b2, ... to the function object, I have to use parentheses around the function object in the Rhino interpreter.

+3  A: 

Your function(a1, a2, ...) { ... } (b1, b2, ...) is invalid, and should return a Syntax Error. ECMAScript has the concept of a FunctionDeclaration as well as that of a FunctionExpression. You may want to check out the following:

While a FunctionExpression is an operator, the FunctionDeclaration is a special syntax used for declaring functions, which are automatically hoisted to the top of the enclosing scope.

Wrapping a function in the grouping operator (parenthesis) will force the interpreter to treat it as a FunctionExpression.

If you try the following in Firebug:

function () { alert('test'); }();       // Syntax Error
(function () { alert('test'); })();     // Works fine
Daniel Vassallo
Thanks a lot! Your answer was exactly what I was looking for. (Actually to me it seems that this particular feature of ECMAScript hasn't been well thought of.)
Marc
@Marc: Yes, I agree. Function expressions should have been enough. There are many situations where function declarations are confusing in this language... This topic was recently discusses in another Stack Overflow post: http://stackoverflow.com/questions/3798984/whats-going-on-in-javascript-when-i-use-the-traditional-c-style-function-decla
Daniel Vassallo
A: 

To execute a function literal, it needs to be enclosed in parentheses. Either:

(function(...){...})(...);

or:

(function(...){...}(...));

Without the parentheses it produces a syntax error.

Guffa
It just has to be made into an r-value. Thus, `!funcion() { ... }` works too.
Pointy