Search code examples
javascriptecma262

Precedence of function object expression in ECMAScript


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.


Solution

  • 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