block scope and function declarations
Allen Wirfs-Brock
allen at wirfs-brock.com
Wed Feb 15 11:23:58 PST 2012
On Feb 15, 2012, at 9:53 AM, Andy Wingo wrote:
> Thanks for the note, Allen.
>
> One remaining doubt:
>
> On Wed, 2012-02-15 at 09:02 -0800, Allen Wirfs-Brock wrote:
>> At the last TC39 meeting it was hypothesized that the block nested
>> function declaration patterns that are actually used inoperably on the
>> web would continue to work if interpreted as lexical (let-like)
>> declarations.
>
> What about "conditional function definition"?
>
> E.g.:
>
> https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Conditionally_defining_a_function
>
> or Oliver's comments here:
>
> https://bugs.webkit.org/show_bug.cgi?id=27226#c5
>
> It seems like a valid use case that needs an answer. The answer might
> be, "just use declarations, assignments, and function expressions";
> dunno.
This is precisely what we discussed at the last TC39 meeting.
if (predicate) {
function foo() {alert("true")}
} else {
function foo() {alert("false")}
}
foo();
does not work interoperability among existing browsers. Under the proposed semantics, the above has a separate block scoped binding for foo in each of the if clauses and the outer reference would most likely be a reference error.
What does work interoperability is something like
if (predicate) {
function foo() {alert("true")}
foo();
}
//note no else clause with an alternative foo definition and no reference to foo outside of the block.
If somebody wants to conditionally define a function an appropriate way to do so would be:
let foo;
if (predicate) {
foo=function foo() {alert("true")};
} else {
foo=function foo() {alert("false")};
}
foo();
or perhaps
function altFoo1() {alert("true")}
function altFoo2() {alert("false")}
let foo;
if (predicate) {
foo=altFoo1};
} else {
foo=altFoo2;
}
foo();
Finally, remember that this is all contingent upon completing web breakage experiments.
Allen
More information about the es-discuss
mailing list