Is the following a bug that needs to be fixed for ES 3.1?
2008/9/4 Michael Daumling <mdaeumli at adobe.com>:
The following code produces a "first is not a function" error:
Array.prototype.first = function()
{ return this.length == 0 ? null : this[0]; }
// no semicolon here
(function() { if ([1,2].first() == 1) alert ("OK"); }())
That's a quite well defined part of automatic semicolon insertion. I don't think it's possible to do anything about it for general script. In a stricter syntax mode or with an external opt-in, one could possibly turn off automatic semicolon insertion except for when semicolons are redundant (such as before closing curlies).
IMHO, there should be a rule that if a function-expression is followed by anything with brackets (), it would require the function-expression to be bracketed as well, otherwise, the bracketed statement does not become part of the assignment.
Not only is that a radical complexification of the automatic semicolon insertion mechanism, it's also an incompatible one.
Can/should this be fixed for 3.1?
Doesn't sound like something for 3.1, and I wouldn't want to see it in Harmony.
Michael Daumling wrote:
Hi all,
The following code produces a "first is not a function" error:
Array.prototype.first = function() { return this.length == 0 ? null : this[0]; } // no semicolon here (function() { if ([1,2].first() == 1) alert ("OK"); }())
If the two statements are separated via a semicolon, there is no error.
The problem is that the second statement is treated as a function argument to the function-expression.
This is not a bug.
A semicolon clearly can't be inserted here because it would change the meaning of a valid program -- as opposed to making an invalid program valid as in other cases of semicolon insertion. (Nor should we even be considering any extensions to semicolon insertion, which is and always was simply a bad idea.)
The program also can't be made invalid because that would be a backward- incompatible change, and because there is no reason to make it invalid.
The following code produces a "first is not a function" error:
Array.prototype.first = function() { return this.length == 0 ? null : this[0]; } // no semicolon here (function() { if ([1,2].first() == 1) alert ("OK"); }())
If the two statements are separated via a semicolon, there is no error.
The problem is that the second statement is treated as a function argument to the function-expression. This illustrates the problem:
x=function(s) { print (s); } ('hi')
This dutifully prints 'hi'.
IMHO, there should be a rule that if a function-expression is followed by anything with brackets (), it would require the function-expression to be bracketed as well, otherwise, the bracketed statement does not become part of the assignment.
Can/should this be fixed for 3.1?
Michael