On 19/10/2005 11:23, Baconbutty wrote:
[Placing function declarations within block statements]
This works fine for me in JScript [...]
That depends on what you define as 'working'. With a conforming
implementation, a syntax error exception would be thrown. That certainly
doesn't happen in most browsers (as I wrote in the other thread I
mentioned).
although admittedly I have not checked the formal grammar in the ECMA
standard,
It's illegal. I misremembered the precise details at the time of the
other thread (thanks again, David), but a function declaration is only
permitted within the SourceElement production. This is available at
'global' scope (within the Program production) or in the body of a
function (FunctionBody). So,
function myFunction() {}
and
function myOuterFunction() {
function myInnerFunction() {
}
}
are both legal, but nothing else is.
Function expressions enter the grammar in the MemberExpression
production, so they may appear in expressions and expression statements.
However, expression statements may not begin with either the 'function'
or '{' tokens (this is what I forgot), so
if(...) {
function() {
}
}
cannot be considered a legal function expression.
or tested in Firefox..
This is where things get interesting. Consider:
if('function' == typeof myFunction) {alert('before');}
if(true) {
function myFunction() {}
}
if('function' == typeof myFunction) {alert('after');}
In IE, both dialogs boxes are shown, so one can only assume that the
'function' token is used to create a function declaration, therefore the
resulting function object is parsed before execution, and available
before the definition is encountered.
In Fx, only the second dialog box is shown, indicating that not only is
the function conditional (a function expression), but that the
identifier - which should only be available to the function expression,
itself - is leaked into the global object, as well.
This can be confirmed by changing the if statement condition to false,
and witnessing the same behaviour in IE, but nothing in Fx.
The leaking behaviour, mentioned above, is equally odd. In IE, it always
appears to leak the identifier when presented with code like:
var global = function local() {};
However, Fx doesn't, even though it did with the previous case.
With all of this conflicting behaviour, the only sensible course of
action is to avoid doing any of this (which is why I'm not going to test
in other browsers).
Mike
--
Michael Winter
Prefix subject with [News] before replying by e-mail.