ES6 中 var 的用例是什么? [英] What is the use case for var in ES6?
问题描述
如果 let
关键字引入了块作用域的正确实现,那么 var
是否还有用例?我是从软件设计的角度而不是从句法的你可以"的角度来看待这个问题的.
If the let
keyword introduces a proper implementation of block scope, does var
any longer have a use case? I am looking at this from a software design standpoint rather than a syntactical, "well you could" standpoint.
推荐答案
如果
let
关键字引入了块作用域的正确实现,那么var
是否还有用例?
If the
let
keyword introduces a proper implementation of block scope, doesvar
any longer have a use case?
可能有一个用例:全局范围内的 let
声明不会在全局对象上创建属性.示例:
There could be one use case: let
declarations in global scope don't create a property on the global object. Example:
"use strict"; // for chrome
var foo = 42;
let bar = 21;
console.log('window.foo (var)', window.foo); // 42
console.log('window.bar (let)', window.bar); // undefined
对象环境记录全局环境记录的组件包含所有内置全局变量的绑定(第 18 条) 以及全局代码中包含的 FunctionDeclaration、GeneratorDeclaration 或 VariableStatement 引入的所有绑定.全局代码中所有其他 ECMAScript 声明的绑定包含在全局环境记录的声明性环境记录组件中.
The object Environment Record component of a global Environment Record contains the bindings for all built-in globals (clause 18) and all bindings introduced by a FunctionDeclaration, GeneratorDeclaration, or VariableStatement contained in global code. The bindings for all other ECMAScript declarations in global code are contained in the declarative Environment Record component of the global Environment Record.
然而,这也可以通过直接分配给全局对象来创建一个显式全局变量来轻松解决:
However, this can also easily be solved by creating an explicit global variable using by assigning to the global object directly:
window.foo = 42;
顺便说一句,这也是创建全局类的唯一方法,因为 class
声明具有相同的行为.
This would also be the only way to create global classes btw, because the class
declaration has the same behavior.
(注意:我不是提倡使用全局变量)
(Note: I'm not advocating the use of global variables)
有些语法结构只能使用 var
,但这更多是规范演变的结果,并没有真正用于任何实际目的.例如:
There are syntax constructs where you can only use var
, but that's more a consequence of the how the spec evolved and doesn't really serve any practical purpose. For example:
if (true)
var foo = 42; // valid but kind of useless or bad design
// vs
if (true)
let foo = 42; // invalid
<小时>
块作用域并不是唯一有用的功能.时间死区是另一个方便的功能可以更轻松地找到错误.比较:
Block scope is not the only useful feature though. The temporal dead zone is another handy feature to find bugs more easily. Compare:
var foo = 42;
function bar() {
console.log(foo); // undefined
var foo = 21;
}
bar();
// vs
var foo = 42; // or `let`, doesn't matter
function bar() {
console.log(foo); // ReferenceError, temporal dead zone
let foo = 21;
}
bar();
尝试访问尚未初始化的 let
变量时出现引用错误.
You get a reference error when trying to access a let
variable that wasn't initialized yet.
这篇关于ES6 中 var 的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!