运行calculateTotal函数报错Cannot access 'usagePrice' before initialization如何解决
问题原因
核心是变量名冲突+JS暂时性死区规则共同导致的报错:
- 全局作用域已经定义了名为
usagePrice的函数 - 在
calculateTotal函数内部,你又通过const usagePrice = usagePrice()声明了一个同名的局部变量 - 根据JS的块级作用域规则,进入
calculateTotal作用域时,JS会先扫描所有const/let声明的变量,将其提升到作用域顶部但不做初始化,这段变量声明语句执行前的区域就叫「暂时性死区」,此区间内访问该变量都会触发未初始化的报错 - 执行
const usagePrice = usagePrice()时,右侧调用usagePrice()会优先匹配当前作用域内的局部usagePrice变量,此时该变量还处于暂时性死区未初始化,就触发了你遇到的报错。
修复方案
有两种常用的修复方式:
- 修改局部变量名,避免和外部函数重名
// Adds all totals together const calculateTotal = () => { // 局部变量换个不冲突的名字即可 const currentUsagePrice = usagePrice(); const currentPrescriptionPrice = prescriptionPrice(); const currentLensPackagePrice = lensPackagePrice(); const currentLensTypePrice = lensTypePrice(); const total = currentUsagePrice + currentPrescriptionPrice + currentLensPackagePrice + currentLensTypePrice; return total; }
- 显式指定调用全局作用域的
usagePrice函数(仅适用于浏览器环境)
const usagePrice = window.usagePrice();
另外注意你当前代码里的prescriptionPrice、lensPackagePrice、lensTypePrice三个函数还没有实现,修复完命名问题后还需要补充这三个函数的定义,否则运行时会触发函数未定义的报错。
内容的提问来源于stack exchange,提问作者Danny Martin
相关产品推荐
相关产品推荐

