Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

let const一章中 块级作用域的第一个例子不正确 #1085

Closed
feeingHe opened this issue Oct 13, 2021 · 3 comments
Closed

let const一章中 块级作用域的第一个例子不正确 #1085

feeingHe opened this issue Oct 13, 2021 · 3 comments

Comments

@feeingHe
Copy link

发现一个书中误区;
原文(第三版,第22页 >> 块级作用域):
第一种场景,内层变量可能会覆盖外层变量。

`var tmp = new Date();

function f() {
console.log(tmp);
if (false) {
var tmp = 'hello world';
}
}
f(); // undefined
`
正确理解此例子:
不是覆盖,f函数内部的变量tmp与外部的tmp变量没有关系。非文中所说覆盖关系;没有外部tmp还是输出同样结果;

@ruanyf
Copy link
Owner

ruanyf commented Oct 14, 2021

如果没有内部变量呢

@ruanyf ruanyf closed this as completed Oct 14, 2021
@feeingHe
Copy link
Author

@ruanyf 哈哈 阮老师好,很高兴收到您的回复,
您也知道函数f解析后,内部tmp已经切断了tmp对外部变量tmp的引用。
【但是“覆盖”的意思,人们会把他理解为,外部tmp也变成了 undefined】
按照您的表述,换成以下例子可能更合适:
var tmp = new Date(); if( true ){ var tmp = 'hello world'; } console.log( tmp )

@Liuxingwei
Copy link

这个“覆盖”指的是“shadowing”,指的是子作用域的同名变量会使用外部变量被屏蔽,在子作用域内默认访问不到外部同名变量的值。或者翻译成“遮蔽”,不容易误会吧。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants