[英]Chrome console: difference between 'let' and 'var'?
I've attached an animated gif to illustrate this weird behavior. 我附上了一个GIF动画来说明这种奇怪的行为。 Essentially, my question is does Chrome console treat
var
and let
differently when used in the same scope? 从本质上讲,我的问题是,Chrome是否控制台治疗
var
并let
不同的在同一范围内使用时? You'll notice that after declaring / assigning a variable, if you try to type that variable's name into the console, Chrome will autocomplete it for you, showing a dropdown list containing what your typing. 您会注意到,在声明/分配变量后,如果您尝试在控制台中输入该变量的名称,Chrome会自动为您自动填充,显示包含您输入内容的下拉列表。 When using
let
s, this is not the case. 使用
let
,情况并非如此。 Is this a bug, feature, or is there something I'm missing about var
and let
in JavaScript? 这是一个错误,功能,还是有什么我缺少关于
var
东西, let
用JavaScript?
Note: I'm well aware that let
lives & dies within the immediate scope. 注意:我很清楚
let
生命和死亡在直接范围内。
When you use var
in the console, it executes in the global scope and adds the variable to the window
object. 在控制台中使用
var
时,它将在全局范围内执行,并将该变量添加到window
对象中。
When you use let
in the console, it executes in the global scope, which doesn't add the variable to the window
object. 在控制台中使用
let
时,它将在全局范围内执行,而不会将该变量添加到window
对象中。
When you start typing, autocomplete checks the parent object for properties to complete along with other language constructs, such as function
, for
, and while
. 当您开始键入时,自动完成检查父对象以查找要与其他语言结构一起完成的属性,例如
function
, for
和while
。
When there is no content in the console, the parent object is window
, which won't have the property you're looking for because let
doesn't add the property to window
. 当控制台中没有内容时,父对象是
window
,它不具有您正在查找的属性,因为let
不会将属性添加到window
。
As soon as you have a new object for autocomplete to complete, behavior returns to what you'd expect. 只要有新的自动完成对象完成,行为就会恢复到您期望的状态。
> let foo = {bar: 'baz'};
> foo.b //autocompletes bar
Now, with all of that said, there's no reason that autocomplete has to behave that way. 现在,所有这些都表明,自动完成必须以这种方式行事。 In many regards the lack of autocomplete for variables defined in global scope via
let
could be considered a "bug" worth "fixing". 在许多方面,通过
let
在全局范围内定义的变量缺乏自动完成可被视为值得“修复”的“错误”。 In my opinion it is moderately surprising behavior. 在我看来,这是一种中度令人惊讶的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.