gpt4 book ai didi

javascript - JS : Why does function declaration order matter when inside a conditional block?

转载 作者:行者123 更新时间:2023-11-28 00:04:51 25 4
gpt4 key购买 nike

a();
function a() {
$('.doit').text('Text was replaced (a)');
}

if ($('.doit2').length) {
b();
function b() {
$('.doit2').text('Text was replaced (b)');
}
}

a() 被正确调用,而 b 给出错误 “b 未定义”。为什么?

(我读过有关提升的内容,但声明了function b,而不是变量。还是我错了?)

参见fiddle - Firefox 抛出错误,而 Chrome 正常。

最佳答案

根据 Javascript 规范,条件语句(或任何其他 block )中不允许使用函数声明。因此,这在技术上是未定义的行为。一些浏览器尝试创建合理的行为。但是,您不应该依赖浏览器能够正确解释这一点。

FunctionDeclarations are only allowed to appear in Program or FunctionBody. Syntactically, they can not appear in Block ({ ... }) — such as that of if, while or for statements.

http://kangax.github.io/nfe/#function-declarations-in-blocks

关于javascript - JS : Why does function declaration order matter when inside a conditional block?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31447259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com