javascript - let 关键字 - 字典数据模型的字典

标签 javascript dictionary ecmascript-6

此查询与存储结构有关,但与了解 let 关键字的作用域规则无关。

<小时/>

使用var关键字,awindow对象(如字典)的属性

var a = 10;
console.log(window.a); // 10
console.log(window['a']) // 10
<小时/>

fwindow对象的属性

function f(){}

console.log(window['f']) // function object
<小时/>

使用let关键字,b不是window字典的属性

let b = 20;
console.log(window.b); // undefined
<小时/>

我的理解是,JavaScript代码中引入的任何名称(function/var/..)都将是window字典(嵌套)对象的属性(成员) .

编辑:

enter image description here

<小时/>

b 是谁的属性(property)?

最佳答案

您提供的代码都与“字典”无关。

varlet 确定变量的范围。使用var,变量的作用域限于其包含的函数(或者全局作用域,如果在所有函数之外)。

let 给出变量 block 级别范围,该范围比函数级别范围更细(即 if/else 语句的分支) .

如果声明位于全局范围内,则 letvar 不会产生任何区别,因为范围是全局的。

两个声明都会创建全局变量,但 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 the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

并且,来自ECMAScript spec. 本身:

let and const 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/

相关文章:

javascript - d3js 图形代码以不同的顺序显示不同数据的 y 轴

javascript - 如何用kineticjs 5.1.0制作作用于多层的橡皮擦?

javascript - 如果在服务器(nodeJS)上运行,此 JavaScript 代码的安全性如何?

javascript - document.removeEventListener() 的问题

python - 通过循环追加 Python 字典列表

python - 访问字典中子字典中的值

Swift 中的字典访问

javascript - ES6 类 : Unexpected token in script?

javascript - 返回对象的 ECMAScript 6 箭头函数

javascript - 如何在 ES6 类中定义类级别常量