是否将函数声明放在返回语句旁边,从而导致函数不起作用?或者将其放入返回语句中,将其转换为函数表达式--这就是为什么它没有被悬挂的原因?
// 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();
发布于 2020-01-01 01:29:28
如果您将一个function放在return关键字后面,它不再是一个函数声明;return只能在其右侧有一个表达式,因此它被解释为一个函数表达式,并且函数表达式不会被悬挂(或者将它们的名称作为一个变量放在周围的作用域中)。
这对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必须是独立语句,而不是通过运算符或关键字直接连接到代码中的任何其他语句。
https://stackoverflow.com/questions/59549471
复制相似问题