← 中文资源

简体中文版本

函数声明提升,函数表达式不提升

函数声明整体提升,声明行之前就能调用;函数表达式按 const 规则处理,提前调用抛 ReferenceError;var 赋值的函数表达式此前只是 undefined。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

declaration hoisted
ReferenceError
expression not hoisted
undefined
function

实现说明

活动部件是函数 expressed、declared。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 expressed、declared。

签名一览:const expressed = ()

核心语句

var legacy = function () { return 'var assigned'; };
const expressed = () => 'expression not hoisted';
return 'declaration hoisted';

代码示例

// Function declarations are fully hoisted: the binding exists and is
// callable from the start of the scope, even above the declaration
console.log(declared());

function declared() {
  return 'declaration hoisted';
}

// Function expressions follow const rules: the binding is hoisted but
// uninitialized, so calling before the assignment throws
try {
  expressed();
} catch (error) {
  console.log(error.constructor.name);
}

const expressed = () => 'expression not hoisted';
console.log(expressed());

// var-assigned function expressions read undefined before assignment
console.log(typeof legacy);
var legacy = function () { return 'var assigned'; };
console.log(typeof legacy);