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

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

问题描述

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

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);

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

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

这种行为很直观:函数 inner 仅在 a==1 时定义.

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

但它如何与范围/提升规则保持一致?

我认为它的定义会被提升到它的作用域的顶部,在 if 块之外,这应该是无效的!

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!

这里是我得到的错误:

浏览器是 Firefox.在这里摆弄.

Browser is Firefox. Fiddle here.

推荐答案

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

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

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天全站免登陆