by Kevin Kononenko

凯文·科诺年科(Kevin Kononenko)

JavaScript变量作用域如何像多个级别的政府一样 (How JavaScript variable scoping is just like multiple levels of government)

Have you ever smashed your keyboard in frustration after getting an undefined value over and over again while trying to find the value of a variable?

在获得未定义的内容后,您是否曾经挫败过键盘? 试图查找变量的值时一遍又一遍地输入值?

Or, have you named two variables the same thing after hours and hours of coding, only to discover your mistake later?

或者,在经过数小时的编码之后,您是否将两个变量命名为同一变量,以便稍后发现错误?

Both of these issues can be related to the scope of your variable. Scope defines where your variables will be accessible throughout your script.

这两个问题都可能与变量的范围有关。 范围定义了在整个脚本中可访问变量的位置。

When you correctly scope your variables, you will find that your code is easier to read and debug for any viewer.

正确确定变量的范围后,您会发现对于任何查看器来说,代码都更易于阅读和调试。

问题 (The problem)

Before the ES6 update to JavaScript, you could only declare variables with var. Since var does not limit the scope of the variable, you would be forced to guess whether the variable had a global scope or local scope.

在将ES6更新为JavaScript之前,您只能使用 var 由于var并不限制变量的范围,因此您将不得不猜测变量是全局范围还是局部范围。

Now, JavaScript allows you to declare variables with const and let. They may add some complexity, but they make your code much easier to understand.

现在,JavaScript允许您使用constlet声明变量 它们可能会增加一些复杂性,但是会使您的代码更容易理解。

Unfortunately, most tutorials describe these scopes as either boxes within boxes or one-way glass. I don’t know about you, but I don’t spend much time packing boxes within boxes or looking through layers of one-way glass!

不幸的是,大多数教程将这些范围描述为盒子内的盒子或单向玻璃。 我不认识你,但是我没有花太多时间在盒子里装盒子或翻阅单层玻璃!

I think I have a better way. Scope can be explained by looking at the ways that international laws, national laws, and local laws work together. So, you only need to understand that different levels of government exist to learn about the different levels of scope. Here’s a quick preview, and then we’ll get into it!

我认为我有更好的方法。 范围可以通过查看国际法,国家法和地方法共同发挥作用的方式来解释。 因此,您只需要了解存在不同级别的政府即可了解不同级别的范围。 这是一个快速预览,然后我们将进行介绍!

I am going to try and avoid any laws that relate to current political issues.

我将尝试避免与当前政治问题相关的任何法律。

全球范围(联合国) (Global scope (United Nations))

Variables that are defined at the top-level of your script are globally scoped. They are available to all functions. These are called global variables.

在脚本顶层定义的变量是全局范围的。 它们可用于所有功能。 这些称为全局变量。

These are similar to international laws. Keep in mind that it is pretty tough to pass laws that all 193 members of the United Nations will agree to. So, these laws should only cover the most fundamental human rights. The United Nations does not get involved in drug policy or religious laws that might concern individual countries. Two examples might be:

这些类似于国际法。 请记住,要通过联合国所有193个会员国都将同意的法律是非常困难的。 因此,这些法律应仅涵盖最基本的人权。 联合国没有介入可能涉及个别国家的毒品政策或宗教法律。 两个示例可能是:

“Torture is prohibited.”

“禁止酷刑。”

“Chemical weapons are prohibited.”

“禁止使用化学武器。”

This means that these laws will be valid for any country that is part of the United Nations, as well as for any state or province within those countries.

这意味着这些法律将对加入联合国的任何国家以及这些国家内的任何州或省有效。

Here is the pre-ES6 version of these laws.

这是这些法律的ES6之前版本。

In ES6, we can now declare variables with const and let. Const will make the value of the variable immutable — it will not be able to be changed. Let will not. I think these two fundamental human rights should definitely be unchangeable! So it should be:

在ES6中,我们现在可以使用constlet声明变量。 常量将使变量的值不可变-将无法更改。 将不会。 我认为这两项基本人权绝对不可改变! 所以应该是:

You don’t want to create too many global variables. ‘Polluting’ the global scope means that you define too many variables that are globally accessible. From a programming perspective, you make it difficult to debug and maintain code when you use global variables.

您不想创建太多的全局变量。 全局范围的“污染”意味着您定义了太多全局可访问的变量。 从编程的角度来看,使用全局变量会使调试和维护代码变得困难。

In this analogy, there are no international laws on the age that individuals are allowed to drink alcohol. Each individual country must define these rules. The UN would never be able to exist if it tried to regulate drinking ages!

以此类推,没有关于允许个人饮酒的年龄的国际法律。 每个国家都必须定义这些规则。 如果联合国试图规范饮酒年龄,它将永远无法生存!

功能范围(美国) (Function scope (United States))

Since the laws above are globally defined, they are accessible anywhere in our script. And, since they are defined with const, they are unchangeable.

由于上述规则是全局定义的,因此可以在脚本中的任何位置访问它们。 并且,由于它们是用const定义的因此它们是不可更改的。

So what about laws that only apply in the United States? One example is the drinking age, the enemy of college students everywhere. You must be 21 years old to buy alcohol in the United States.

那么,仅适用于美国的法律呢? 一个例子是饮酒时代,到处都是大学生的敌人。 您必须年满21岁才能在美国购买酒。

Should this age be immutable or unchangeable? No. In fact, there was no universal law on drinking age in the US until 1984. It could change again in the future.

这个年龄应该不变还是不变? 否。事实上, 直到1984年,美国才没有关于饮酒年龄的普遍法律 。 将来可能会再次改变。

We will use let to define this one.

我们将使用let来定义这一点。

If we try to access the value of drinkingAge outside of the unitedStates function, we will get an error since it only exists within the function scope.

如果我们试图访问UnitedStates的功能drinkingAge之外的价值,我们会因为它只作用范围内的存在得到一个错误。

Just remember — the UN’s laws are still valid in the United States.

请记住,联合国的法律在美国仍然有效。

The brackets are like the borders of the country, in this case. Laws are only valid within the borders of that country. So, if you wanted to create a mexico function, you could define drinkingAge again as 18.

在这种情况下,方括号就像国家的边界​​。 法律仅在该国境内有效。 因此,如果您要创建墨西哥函数,则可以再次将DrinkingAge定义为18。

Here is that code in diagram form.

这是图表形式的代码。

块范围(马萨诸塞州) (Block scope (Massachusetts))

I live in Massachusetts, so I decided to pick on my own state for this one. There is one other level of scope: block scope. Block scope and function scope are both examples of local scope, since they create local limits for the definition of variables.

我住在马萨诸塞州,所以我决定选择自己的州。 还有另一种范围: 块范围 。 块作用域和函数作用域都是局部作用域的示例因为它们为变量定义创建了局部限制。

Block scope means that a variable can be local to a set of brackets {}, like an if statement or for loop. Much like function scope, the variable is only valid within those brackets.

块作用域意味着变量可以位于一组括号{}中,例如if语句或for循环。 就像函数作用域一样,变量仅在这些括号内有效。

In Massachusetts, all bars must stop serving at 2AM. I know, I know — if you live in Europe, this probably sounds outrageous. This law actually varies by state. In New York, they can serve until 4AM.

在马萨诸塞州,所有酒吧必须在凌晨2点停止服务。 我知道,我知道-如果您住在欧洲,这听起来太离谱了。 该法律实际上因州而异。 在纽约,他们可以服务到凌晨4点。

Anyway, in order to make this work in code, we need to define if statements within the unitedStates function. We will again define the variable with let, because these laws can certainly change.

无论如何,为了使它在代码中起作用,我们需要定义 unitedStates函数中的if语句。 我们将再次使用let定义变量,因为这些定律肯定会发生变化。

The closingTime variable is only valid within the if block, while drinkingAge is valid anywhere in the unitedStates function.

关闭时间变量仅在if块内有效,而DrinkingAge在unitedStates函数中的任何位置均有效。

If we want to define a separate closing time for New York, we can do that as well due to block scope.

如果我们想为纽约定义一个单独的关闭时间,由于块范围 ,我们也可以这样做。

If you wanted to take action based on the closingTime variable, you could now do something within each if block.

如果您想基于闭合时间变量执行操作,现在可以在每个if块内执行一些操作。

Here is a diagram that covers all this.

这是涵盖所有内容的图表。

修改变量(通过新法律) (Modifying a variable (passing a new law))

Last part. Let’s say you want to pass a law to change the drinking age in the United States. You need to create a function that will be able to modify the drinkingAge variable. Let’s call it passDrinkingLaw.

最后部分。 假设您想通过一项法律来更改美国的饮酒年龄。 您需要创建一个函数,该函数将能够修改DrinkingAge变量。 我们称之为passDrinkingLaw

You will need to create the passDrinkingLaw function within the unitedStates function, because it is only relevant to the US. There are no global drinking laws.

您将需要在unitedStates函数内创建passDrinkingLaw函数,因为它仅与美国有关。 没有全球饮酒法。

It will also need to access the drinkingAge variable, which defined the original age. Imagine that you wanted to change the drinking age to 18. Here is how you would do that.

它还需要访问drinkingAge变量,该变量定义了原始年龄。 想象一下,您想将饮酒年龄更改为18岁。这就是您的做法。

This is why it is important to define the variable within the entire unitedStates scope. You would want the changes to take effect for any future use of drinkingAge. And, if you wanted to create a universal passDrinkingLaw function, it would not work with this structure.

这就是为什么在整个unitedStates范围内定义变量很重要的原因。 您可能希望这些更改对将来的DrinkingAge使用生效。 而且,如果您想创建通用的passDrinkingLaw函数,则该函数不适用于此结构。

drinkingAge is local to the unitedStates funtion. Here is a diagram version.

DrinkingAge是美国功能的本地版本。 这是一个图表版本。

呼吁采取行动 (Call To Action)

Did you enjoy this? Give it a clap so others can discover it as well. And, if you want to get notified when I release future tutorials that use analogies, sign up here:

你喜欢这个吗? 给它鼓掌,以便其他人也可以发现它。 而且,如果您希望在以后发布使用类比的教程时得到通知,请在此处注册:

翻译自: https://www.freecodecamp.org/news/how-javascript-variable-scoping-is-just-like-multiple-levels-of-government-d7ddabc49bf1/

JavaScript变量作用域如何像多个级别的政府一样相关推荐

  1. JavaScript变量作用域和内存问题(js高级程序设计总结)

    1,变量 ECMAScript和JavaScript是等同的吗?个人认为是否定的.我的理解是这样的,ECMAScript是一套完整的标准或者说协议,而JavaScript是在浏览器上实现的一套脚本语言 ...

  2. 实例浅析javascript变量作用域

    全局域变量在局部可见,局部变量在全局不可见 var global_value = 'global value';  func(); console.log(local_value); function ...

  3. javascript变量作用域一点总结

    前言:javascript里变量作用域是个经常让人头痛抓狂的问题,下面通过10++个题目,对经常遇到又容易出错的情况进行了简单总结,代码样例很短很简单 题目一 var name = 'casper'; ...

  4. javascript 变量作用域

    为什么80%的码农都做不了架构师?>>>    javascript中的变量的作用域不同于java/c的变量规则. 1.在java/c中,如果有一个全局变量与一个局部变量重名,那么在 ...

  5. javascript变量声明 及作用域

    javascript变量声明提升(hoisting) http://openwares.net/js/javascript_declaration_hoisting.html 可能要FQ一下 java ...

  6. mysql变量作用域,变量作用域 | 类型、变量和值 | JavaScript 权威指南

    变量作用域 由 学院君 创建于1年前, 最后更新于 1年前 版本号 #2 724 views 0 likes 0 collects 变量的作用域指的是程序源码中定义这个变量的区域,全局变量具有全局作用 ...

  7. 深入理解JavaScript的变量作用域

    在学习JavaScript的变量作用域之前,我们应当明确几点: a.JavaScript的变量作用域是基于其特有的作用域链的. b.JavaScript没有块级作用域. c.函数中声明的变量在整个函数 ...

  8. JavaScript的变量作用域深入理解(转)

    在学习JavaScript的变量作用域之前,我们应当明确几点:  a.JavaScript的变量作用域是基于其特有的作用域链的.  b.JavaScript没有块级作用域.  c.函数中声明的变量在整 ...

  9. 深入理解JavaScript的变量作用域(转)

    在学习JavaScript的变量作用域之前,我们应当明确几点: a.JavaScript的变量作用域是基于其特有的作用域链的. b.JavaScript没有块级作用域. c.函数中声明的变量在整个函数 ...

最新文章

  1. 图像识别 43个模型
  2. R语言实战应用精讲50篇(二十七)-时空数据分析-经验空间/时间均值(latex公式+R代码绘图)
  3. 混合式安全灵活性可充分满足无边界企业的发展
  4. python list去重时间复杂度_List集合去重的一种方法 z
  5. 链表C++ | 根据 位置 / 值 删除节点_2
  6. Communicator可以多点同时Logon
  7. 循序渐进!java读文件并重新写文件
  8. 计算机开放电子书 2016 归档
  9. 死磕jdk源码之如何注释
  10. hibernate 注解方式 属性mappedBy详解
  11. 笔记本作服务器配置无线网卡,如何利用笔记本电脑的无线网卡搭建局域网
  12. P3717 [AHOI2017初中组]cover
  13. AI研习丨针对长尾数据分布的深度视觉识别
  14. 计算机硬盘分区和盘符,硬盘怎么分区,教您硬盘怎么分区
  15. ping 不通百度问题的解决
  16. 加加米-又一网络营销中的异军突起!新生的尖锐之师
  17. 5万字 TypeScript入门系列(第四期)(建议收藏)
  18. 光伏辐照和发电功率数据集
  19. c语言程序和数据是可执行,C语言学习笔记(C编程-Tan Haoqiang)
  20. C++: 计算其元素受制于的矩阵的逆模算术(附完整源码)

热门文章

  1. 类与对象的小结 java 1614782140
  2. 06 使用VS2012开发简单控制器程序 1214
  3. 190829课堂母版与子版
  4. juqery-筛选器-找前后上下
  5. Closure 代表匿名函数的类
  6. js实现文章显示部分内容
  7. shell介绍 命令历史 命令补全和别名 通配符 输入输出重定向
  8. 网络分析仪-inSSIDer
  9. cocos2dX之一——安卓环境搭建
  10. 用 npm script 实现服务自动化运维