JavaScript中的内部函数会被挂起吗?范围规则如何适用于他们? [英] Do inner functions in JavaScript get hoisted? How do the scoping rules apply to them?

查看:114
本文介绍了JavaScript中的内部函数会被挂起吗?范围规则如何适用于他们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为JavaScript没有块范围,但是函数作用域,并且声明从它们的块被提升到其父函数的顶部。

然而,

然而, ,以下代码无法按预期工作:

  function one(a){
console.log(one要求+ a);

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

inner(123);
}

inner(456);
}

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

第一个一(1); 调用正常进行,没有任何错误,但是当调用第二个 one(2); 时停止执行。



这种行为很直观:只有在 a == 1 时才定义内部函数



但它与范围/提升规则是一致的吗? 我认为它的定义将被提升到它的作用域的顶部,在 if if 块之外,应该是没有效果的!

编辑:这里是我得到的错误:





浏览器是Firefox。 小提琴在这里。

解决方案

如果(...){
函数...(){
...
}
}

  


是无效的ECMAScript。函数声明必须位于函数或程序体的顶层,位于块的内部它们的行为取决于实施情况。 Firefox会有条件地执行这个函数语句,其他浏览器会像正常的函数声明那样提升它。将它移到if语句之外,或者分配一个函数表达式。


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:

Browser is Firefox. Fiddle here.

解决方案

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

is invalid ECMAScript. Function declarations must be on the top level of function or program bodies, inside of blocks their behaviour is implementation-dependent. Firefox does execute this function statement conditionally, other browsers do hoist it like a normal function declaration. Move it outside the if-statement, or assign a function expression.

这篇关于JavaScript中的内部函数会被挂起吗?范围规则如何适用于他们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆