为什么JavaScript中没有挂起回调函数

Why are callback functions not hoisted in JavaScript?

本文关键字:挂起 回调 函数 JavaScript 为什么      更新时间:2023-09-26

我理解JavaScript中的变量和函数声明的概念,它们被挂在封闭范围的顶部。但如果我有一个命名的回调函数,它不会被提升。我不明白为什么会这样。我在下面的链接中有解释场景的代码

示例:

function enclosingScope () {
  var b;
  function inner (def) {
    def();  
  }
  var a = 2;
}
// After hoisting due to compilation, the above changes to 
function enclosingScope () {
  // Function declarations are hoisted before variables
  function inner (def) {
    def(); 
  }
  var b, a;
  a = 2
}
// But if I have a named callback, will that be hoisted?
function enclosingScope () {
  function inner (def) {
    def();
  }
  var b, a;
  a = 2
  inner(function cb () {
    console.log('Test callback hoisting')
  })
}

我发现给出的答案太短,所以这里有一个更规范的解释:

Javascript区分函数声明

function f() {}

和函数表达式

var f = function () {} // anynomous function or lambda
var g = function h() {} // named function expression

函数声明是语句,而函数表达式是。。。,你猜怎么着?耶,表情。请注意,命名函数表达式(在给定示例中为h)的名称只能在函数体(在给定实例中为g)内部访问。

无论何时将函数声明嵌套在圆括号中,它都会自动转换为表达式。这意味着您的function cb () {...}只是一个命名函数表达式。但您不将其分配给变量,而是将其作为参数传递给inner

当涉及到与函数表达式相关的提升时,只会提升指定变量的声明。函数声明的情况并非如此:

console.log(f); // function f
console.log(g); // exists, but undefined
console.log(h); // reference error
function f() {}
var g = function h() {}

由于示例中的cb没有分配给变量,因此不可能有提升。

因此,这两条线在起重方面是等效的:

inner(function cb(){});
(function cb(){});

奖金:const/let

然而,当您试图调用用constlet声明的函数表达式时,在其声明之前,会抛出一个引用错误:

console.log(g); // reference error
const g = function h() {}

g也被吊起。但为了保护您免受意外的undefineds的影响,解释器抛出了一个错误。我认为这是明智的。

有问题的行为不限于命名回调。这是任何命名函数表达式的工作方式。考虑以下内容:

function foo() {
  (function baz() { });
  console.log(typeof baz);
}
> foo()
< undefined

baz在其体外是不可接近的。所以这是一个不同于吊装的问题。