2

I thought that JavaScript doesn't have block scope, but function scope, and that declarations are hoisted from their block to the top of their parent functions.

However, the following code does not work as expected:

function one(a) {
    console.log("one called for " + a);

    if (a == 1) {
        function inner(b) {
            console.log("inner called for " + b);
        }

        inner(123);
    }

    inner(456);
}

one(1);
one(2);
one(3);

The first one(1); call proceeds normally, without any errors, however the execution stops when the second one(2); is called.

This behavior is intuitive: the function inner is defined only if a==1.

But how is it consistent with the scoping/hoisting rules?

I thought its definition would be hoisted to the top of its scope, outside of the if block which is supposed to have no effect!

Edit: here are the errors I am getting:

screenshot of Firefox console showing the error

Browser is Firefox. Fiddle here.

4

2 回答 2

2
if (…) {
    function …() {            
        …
    }
}

是无效的 ECMAScript。函数声明必须在函数或程序体的顶层,在块内部,它们的行为是依赖于实现的。Firefox 确实有条件地执行这个函数语句,其他浏览器会像普通函数声明一样提升它。将其移到 if 语句之外,或分配一个函数表达式。

于 2014-02-24T12:29:34.977 回答
1

的声明inner被提升到外部函数的顶部。但是,它的值仅在 时设置a == 1

outer()使用不同的值调用时,调用inner(456)失败,因为inner仍然设置为undefined.

于 2014-02-24T10:31:04.673 回答