变量 Shadowing
快速摘要
你 declared 变量使用相同 name as one in 外部作用域 — 内部变量 hides 外部 one, causing confusion.
为什么发生
Using 相同变量 name in nested 作用域
Reusing 常见 names 如 i, x, or 数量 in 内部块
Naming 局部变量相同 as 全局 or 参数
最小示例
✗ 错误代码
let x = 10;
function test() {
let x = 20; // Shadows outer x!
console.log(x); // 20, not 10
}
test();✓ 修复代码
let x = 10;
function test() {
let innerX = 20; // Distinct name
console.log(x, innerX); // 10, 20
}
test(); 内部 let x = 20 shadows 外部 let x = 10. 内部函数, x refers 到局部 20. Renaming 内部变量制作 code clearer and avoids confusion.
如何诊断
检查如果变量值 是不同从 什么你 expect
Look for 变量使用相同 name in 不同作用域
Use 你的 editor's '查找所有引用' 到 see 所有 declarations
如何修复
Rename 内部变量到 某事 distinct
Use 更多 descriptive 变量 names 到 avoid collisions
Access 外部变量通过不同引用如果需要
如何预防
Use descriptive, 唯一变量 names
Avoid reusing 循环计数器 names (i, j) in nested 函数
相关资源
相关课程
- 作用域 and Visibility
学习关于作用域 and shadowing.