Chrome console: difference between 'let' and 'var'?

ⅰ亾dé卋堺 提交于 2020-01-01 09:42:11

问题


I've attached an animated gif to illustrate this weird behavior. Essentially, my question is does Chrome console treat var and let differently when used in the same scope? 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. When using lets, this is not the case. Is this a bug, feature, or is there something I'm missing about var and let in JavaScript?

Note: I'm well aware that let lives & dies within the immediate scope.


回答1:


When you use var in the console, it executes in the global scope and adds the variable to the window object.

When you use let in the console, it executes in the global scope, which doesn't add the variable to the window object.

When you start typing, autocomplete checks the parent object for properties to complete along with other language constructs, such as function, for, and 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.

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". In my opinion it is moderately surprising behavior.




回答2:


var defines a variable on the global scope, while let defines it only in the local scope. Most likely, the autocomplete is only looking on the global scope for targets.



来源:https://stackoverflow.com/questions/39397126/chrome-console-difference-between-let-and-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!