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

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值