Chrome控制台:'let'和'var'之间的区别? [英] Chrome console: difference between 'let' and 'var'?

查看:800
本文介绍了Chrome控制台:'let'和'var'之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我附上了一个动画gif来说明这种奇怪的行为。从本质上讲,我的问题是Chrome控制台在同一个作用域中使用时,会不同地处理 var let 的方式不同?您会注意到,在声明/分配变量后,如果您尝试将该变量的名称输入控制台,Chrome会为您自动填充该变量,并显示包含您输入内容的下拉列表。当使用 let s时,情况并非如此。这是一个错误,功能还是我在JavaScript中缺少有关 var let 的信息?



注意:我很清楚生命&死在眼前的范围内。



解决方案当你在控制台中使用 var 时,它会在全局范围内执行并将变量添加到窗口中 c $ c> object。

在控制台中使用 let 时,它会在全局范围内执行,不会将变量添加到窗口对象中。



当您开始输入时,autocomplete会检查父对象属性与其他语言结构一起完成,例如函数用于,而



当控制台中没有内容时,父对象是 window ,因为 let 不会将属性添加到窗口中。 / p>

只要有一个用于完成自动填充的新对象,行为就会返回到您期望的状态。

 >让foo = {bar:'baz'}; 
> foo.b // autocompletes bar






现在,所有这一切说,没有理由自动完成这样的行为。在很多方面,通过 let 在全局范围中定义的变量缺乏自动完成可以被认为是值得修复的bug。在我看来,这是一种适度惊人的行为。

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.

解决方案

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.

这篇关于Chrome控制台:'let'和'var'之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆