首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果将命名函数声明放在return语句中,它为什么不被挂起?

如果将命名函数声明放在return语句中,它为什么不被挂起?
EN

Stack Overflow用户
提问于 2020-01-01 01:27:00
回答 1查看 84关注 0票数 1

是否将函数声明放在返回语句旁边,从而导致函数不起作用?或者将其放入返回语句中,将其转换为函数表达式--这就是为什么它没有被悬挂的原因?

代码语言:javascript
复制
// Hoisting doesn't work in here
function outer() {
  console.log(inner); // Isn't hoisted
  return function inner() {
    console.log("hello world");
  };
}
outer();

代码语言:javascript
复制
// Works in here
function outer() {
  console.log(inner);

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-01 01:29:28

如果您将一个function放在return关键字后面,它不再是一个函数声明;return只能在其右侧有一个表达式,因此它被解释为一个函数表达式,并且函数表达式不会被悬挂(或者将它们的名称作为一个变量放在周围的作用域中)。

这对return来说并不是什么特别的事情。强制将function部件解释为表达式的任何其他关键字都具有相同的效果:

代码语言:javascript
复制
function outer() {
  console.log(typeof inner); // Isn't hoisted
  if (function inner() {
    console.log("hello world");
  }) {
  }
}
outer();

代码语言:javascript
复制
function outer() {
  console.log(typeof inner); // Isn't hoisted
  switch (function inner() { console.log("hello world"); }) {
  
  }
}
outer();

代码语言:javascript
复制
function outer() {
  console.log(typeof inner); // Isn't hoisted
  const x = function inner() {
    console.log("hello world");
  };
}
outer();

要将函数解释为函数声明(函数声明是唯一被悬挂的函数),function必须是独立语句,而不是通过运算符或关键字直接连接到代码中的任何其他语句。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59549471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档