简体   繁体   English

Javascript Shadowing-如果您尝试使用VAR关键字更改不存在的全局变量而产生的影响

[英]Javascript Shadowing - Effect if you try to change an already existing global variable w/o using the VAR keyword

So, I understand that declaring a variable without the var keyword means it's declared in the global scope. 因此,我知道声明不带var关键字的变量意味着它是在全局范围内声明的。

So in the 1st example below, Line 4 of the code changes the global variable person (which does not have the var keyword preceding it) from "Jim" to "Andrew." 因此,在下面的第一个示例中,代码的第4行将全局变量person (在其前面没有var关键字)从“ Jim”更改为“ Andrew”。

var person = "Jim";

function whosGotTheFunc() {
   person = "Andrew";
}

person = "Nick";
whosGotTheFunc();
console.log(person);

And in the 2nd example, Line 4 of the code creates a separate local variable, also entitled person . 在第二个示例中,代码的第4行创建了一个单独的局部变量,也称为person

var person = "Jim";

function whosGotTheFunc() {
   var person = "Andrew";
}

person = "Nick";
whosGotTheFunc();
console.log(person);

However, what does Line 7 of both examples do? 但是,两个示例的第7行做什么? The line that says: person = "Nick"; 这行代码说: person =“ Nick”;

The Treehouse quiz asks what is logged to the console. Treehouse测验询问要记录到控制台的内容。 In example #1, Line 4 changes the global variable person to "Andrew" but then Line 7 does NOT affect that global variable (so the console logs "Andrew")... However, in example #2, after Line 4 creates a local variable, Line 7 does, in fact, change the value of the global variable from "Jim" to "Nick" (the console logs "Nick"). 在示例#1中,第4行将全局变量person更改为“ Andrew”,但是第7行不会影响该全局变量(因此控制台记录了“ Andrew”)...但是,在示例#2中,第4行创建了一个局部变量,实际上,第7行​​确实将全局变量的值从“ Jim”更改为“ Nick”(控制台日志为“ Nick”)。

What I want to know is in the 2 examples, why the difference in behavior of Line 7: person = "Nick"??? 我想知道的是在两个示例中, 为什么第7行的行为不同:person =“ Nick” ???

The variable is modified in both examples. 在两个示例中均修改了该变量。 However, the call to whosGotTheFunc() is after the global modification, so in the first example, it overwrites the value of "Nick", leaving it at "Andrew". 但是,对whosGotTheFunc()的调用是全局修改之后进行的,因此在第一个示例中,它将覆盖“ Nick”的值,而将其保留为“ Andrew”。

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

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