简体   繁体   English

scope 和块范围如何在 JavaScript 中工作?

[英]How does scope and block scoping work in JavaScript?

I'm a newbie in JavaScript and trying to learn about Objects and for..in loop.我是 JavaScript 的新手,并试图了解对象和 for..in 循环。

Then I tried this code in the browser:然后我在浏览器中尝试了这段代码:

const dad = {
    gender: 'male',
    age: 53
}

for(let prop in dad){
    console.log(prop, dad[prop]);
}

It showed the result once, but then when I run again, the console says:它显示了一次结果,但是当我再次运行时,控制台显示:

Uncaught SyntaxError: Identifier 'dad' has already been declared

I've tried to do some Google search and read through about scope and block scoping, but still not yet really understand我尝试做一些谷歌搜索并阅读有关 scope 和块范围,但还没有真正理解

When I tried to block the code with an outer scope ( grap the code in a {} ) or put the code in a function, it works well.当我尝试使用外部 scope (将代码放在{}中)或将代码放入 function 来阻止代码时,它运行良好。

Please help me understand this请帮助我理解这一点

The console does run code snippets in the global scope.控制台确实在全局 scope 中运行代码片段。 When you've run const dad for the first time, it does declare a global variable.当您第一次运行const dad时,它确实声明了一个全局变量。 You now can refer to dad in subsequent code.您现在可以在后续代码中引用dad When you try to run it a second time, it complains that it already is declared - just as if you had written当您尝试第二次运行它时,它会抱怨它已经被声明了 - 就像您已经写了一样

const dad = 1;
const dad = 2;

If you want to start fresh, reload the page.如果您想重新开始,请重新加载页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM