You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中函数为何能访问后续声明的变量?

为什么全局作用域无法访问后续声明的const变量,但内部函数可以?

先看你给出的代码示例:

const hoistedName = "Adam" + " " + lastname // cannot read lastname

var hello = (name) => {
  const fullname = name + " " + lastname // can read lastname delared afterward
  console.log(`hello ${fullname}`)
}

const lastname = "Smith" // variable declared

hello("John")  // => hello John Smith

console.log(hoistedName) // => Adam null

核心原因是代码执行时机的差异,结合const的变量提升和暂时性死区(TDZ)特性来理解:

  • 全局作用域的即时执行:
    全局代码是从上到下逐行执行的。当执行到const hoistedName = ...这一行时,lastname虽然已经被提升到全局作用域顶部,但const声明的变量在其实际声明语句const lastname = "Smith"之前,处于暂时性死区——此时变量已经存在但无法被访问,所以这行代码实际会直接抛出ReferenceError(你代码里的Adam null应该是错误模拟,真实环境中这一步会报错)。

  • 函数的延迟执行:
    hello箭头函数被定义后并没有立即执行,直到你在lastname完成声明和赋值后调用hello("John")。当函数执行时,它会沿着作用域链向上查找lastname:此时全局作用域里的lastname已经脱离暂时性死区,能正常读取到"Smith",所以可以拼接出完整的全名。

简单说:全局代码是即时执行,碰到还在TDZ里的变量直接报错;函数是延迟执行,等调用时后续声明的变量已经可用,自然能访问到。

内容的提问来源于stack exchange,提问作者Eric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:12:29