此查询与存储结构有关,但与了解 let
关键字的作用域规则无关。
使用var
关键字,a
是window
对象(如字典)的属性
var a = 10;
console.log(window.a); // 10
console.log(window['a']) // 10
<小时/>
f
是window
对象的属性
function f(){}
console.log(window['f']) // function object
<小时/>
使用let
关键字,b
不是window
字典的属性
let b = 20;
console.log(window.b); // undefined
<小时/>
我的理解是,JavaScript代码中引入的任何名称(function/var/..)都将是window
字典(嵌套)对象的属性(成员) .
编辑:
<小时/>
b 是谁的属性(property)?
最佳答案
您提供的代码都与“字典”无关。
var
与 let
确定变量的范围。使用var
,变量的作用域限于其包含的函数(或者全局作用域,如果在所有函数之外)。
let
给出变量 block 级别范围,该范围比函数级别范围更细(即 if
/else
语句的分支) .
如果声明位于全局范围内,则 let
与 var
不会产生任何区别,因为范围是全局的。
两个声明都会创建全局变量,但 let
不会像 var
那样在 window
对象上显式创建命名属性.
参见this 了解详情。
同样来自 MDN :
let
allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike thevar
keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
并且,来自ECMAScript spec. 本身:
let
andconst
declarations define variables that are scoped to the running execution context’s LexicalEnvironment.A
var
statement declares variables that are scoped to the running execution context’s VariableEnvironment.
这就是为什么全局声明的 let
变量不能像全局声明的 var
变量一样通过 window
访问。
关于javascript - let 关键字 - 字典数据模型的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46124619/