gpt4 book ai didi

javascript - 如果将命名函数声明放在 return 语句中,为什么它不会被提升?

转载 作者:行者123 更新时间:2023-11-30 09:10:24 25 4
gpt4 key购买 nike

是否将函数声明放在返回语句旁边导致函数无法提升?或者将它放在 return 语句中将它变成一个函数表达式,这就是它没有被提升的原因?

// Hoisting doesn't work in here
function outer() {
console.log(inner); // Isn't hoisted
return function inner() {
console.log("hello world");
};
}
outer();

// Works in here
function outer() {
console.log(inner);

function inner() {
console.log("hello world");
}
return inner;
}
outer();

最佳答案

如果在return 关键字之后紧跟一个function,它就不再是一个函数声明; return 只能在它的右边有一个 expression,所以它被解释为一个函数表达式,并且函数表达式不会被提升(或者将它们的名字放在周围范围作为变量)。

这不是return 特有的东西。强制将 function 部分解释为表达式的任何其他关键字都将具有相同的效果:

function outer() {
console.log(typeof inner); // Isn't hoisted
if (function inner() {
console.log("hello world");
}) {
}
}
outer();

function outer() {
console.log(typeof inner); // Isn't hoisted
switch (function inner() { console.log("hello world"); }) {

}
}
outer();

function outer() {
console.log(typeof inner); // Isn't hoisted
const x = function inner() {
console.log("hello world");
};
}
outer();

对于被解释为函数声明的函数(函数声明是唯一被提升的函数),function 必须是一个独立的语句,不能直接连接到通过运算符或关键字编码。

关于javascript - 如果将命名函数声明放在 return 语句中,为什么它不会被提升?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59549471/

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