「这是我参与2022首次更文挑战的第6天,活动详情查看:2022首次更文挑战」。
前言
前段时间有道面试题,关于let的变量提升,寻根究底发现MDN中有个词,Lexical Enviroment,中文:词法作用域,这究竟是个什么东东,就又搜了一下。
有篇文章写的还蛮通俗易懂的,可惜是纯英文文章,所以就顺便翻译过来。原文地址:jstutorial.medium.com/javascript-…
ps:需要合理使用梯子才能看到。只对内容感兴趣的小可爱可以只看我后面的翻译。
正文内容
Lexical Environment in JavaScript is created every time you create a scope using the curly brackets {}. It can be nested: {{…}}
Javascript中的词法环境会在每次你使用 {} 时被创建出来。它可以被嵌套,在代码中就是{{}}。
A Lexical Environment is created behind the scenes. It’s just a logistical concept. There is no way to actually access it from your JavaScript code.
词法环境可以在幕后创建 。这是一个逻辑概念。实际上不能从Javascript代码中访问它。
You may have been creating Lexical Environments all along. You just didn’t know it. In this diagram each LE is color-coded. It’s a very subtle but important feature.
你可能一直在创建词法环境,只是你不知道罢了。在上面这张图中,每个词法作用域都是用颜色编码的。这是一个非常微妙但是很重要的特征。
Using scope brackets, you can determine the structure of your computer program. Together with data types, functions and variable definitions you can craft an entire application structure that determines its data conduit:
使用范围括号,您可以确定计算机程序的结构。与数据类型、函数的变量定义在一起,你可以构建一个完整的应用程序结构来决定它的数据管道:
The scope (same as lexical context) determines the way your data will travel throughout your application via statements and expressions.
范围(与词法上下文相同)决定了数据通过语句和表达式在整个应用程序中传输的方式。
If you don't understand Lexical Environments it will be difficult to understand the difference between let and var keywords.
如果你不理解词法环境,那么就很难理解let和var关键字之间的区别。
The let keyword conceals that variable to its own scope. It provides data privacy because sometimes you want to limit the use of a variable to a scope.
Let 关键字将该变量隐藏到它自己的作用域中。它提供了数据隐私,因为有时您希望将变量的使用限制在某个范围内。
The var keyword “hoists” (or lifts up) the variable definition (its name) up all the way to the global scope. Regardless what block-scope your variable is defined in using var, it always becomes available at the uppermost scope.
Var 关键字“ hoists”(或提升)变量定义(其名称)一直提升到全局作用域。无论在使用 var 时定义了哪个 block-scope 变量,它总是在最上面的作用域可用。
For these reasons the let keyword is considered to be a “safer” alternative to the var keyword, even though in a few cases they produce exactly the same behavior. The difference is that let always conceals to the scope its defined in.
由于这些原因,let 关键字被认为是 var 关键字的“更安全的”替代品,尽管在少数情况下它们产生完全相同的行为。不同之处在于,我们总是将其定义的范围隐藏起来。
There are exceptions. Variables defined inside function-scope are concealed to it — regardless of whether you used var or let. This is also true of callback functions (which are essentially are function-scope.)
也有例外。在 function-scope 中定义的变量被隐藏在其中ーー不管您是否使用 var 或 let。对于回调函数也是如此(它们本质上是 function-scope.)
--- END ----