gpt4 book ai didi

javascript - 将函数语句放在 if 语句中

转载 作者:行者123 更新时间:2023-11-28 15:30:00 26 4
gpt4 key购买 nike

我听说有人声称在 JavaScript 上下文中将函数语句放在 if 语句中是不好的做法。为什么会这样?

最佳答案

这是一种不好的做法,因为函数声明被“提升”到词法作用域的顶部不关心您的代码是否进入 if 语句的该部分。

例如:

var someFunction = function () {
var num = 5;

if ( num !== 5 ) {
function anotherFunction () {
console.log( 'hello there' );
}
}

anotherFunction();
};

someFunction(); // logs out 'hello there'

尽管anotherFunction表面上是在if语句中声明的,但这对JavaScript引擎来说并不重要,因为所有函数声明都会被提升到词法作用域的顶部(在本例中,到 someFunction 函数的词法作用域的顶部)。这就是为什么可以在 if 语句之外调用 anotherFunction 的原因。

在以下情况下会变得更加麻烦:

var someFunction = function () {
var num = 5;

if ( num === 5 ) {
function anotherFunction () {
console.log( 'hello there' );
}
} else {
function anotherFunction () {
console.log( 'bye bye' );
}
}

anotherFunction();
};

someFunction(); // logs out 'bye bye'

期望结果是“hello world”,但第二个场景记录“bye bye”的原因是因为 JavaScript 引擎将所有函数声明提升到词法作用域的顶部。当它提升第一个函数声明时,标识符“anotherFunction”用“hello there”引用函数对象。然而,当它提升第二个函数声明时,它只是将另一个函数对象(带有“bye bye”的函数对象)分配给现有标识符anotherFunction

您可以看到这是多么误导和困惑,因为它违背了您的期望。

关于javascript - 将函数语句放在 if 语句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760374/

26 4 0