javascripts范围

JavaScript的作用域是什么? (What is Scope in JavaScript?)

In JavaScript, Scope refers to where something is available to us. It is defined by where variables are declared and where they are available for us to use. JavaScript is a bit wild sometimes but with a strong understanding of scope we can tame it and control the flow of our code so it is readable and strong.

在JavaScript中, 范围是指我们可以使用的内容。 它由声明变量的位置以及可供我们使用的变量定义。 JavaScript有时有点狂野,但是对范围的了解很深,我们可以驯服它并控制代码流,使其可读性强。

Javascript has two scopes we can utilize: Global and Local. We will get into the nitty gritty of each later in this blog. To put it simply, Global scope refers to anything declared outside of a block of code and Local Scope refers to anything declared inside a block of code.

我们可以利用Javascript的两个作用域:Global和Local。 在本博客的后面,我们将深入探讨每个问题。 简单来说, 全局范围是指在代码块之外声明的任何内容,而本地范围是指代码块内部声明的任何内容。

Let’s use an example from the real world to help us understand how this works. In any office or work place, there is a hierarchy starting at the top with a CEO that works it’s way down to the entry level employees. The CEO hypothetically has all of the information regarding the company, followed by the management team, team leads, and entry level employees. However, each of those sub-teams has their own lingo, conversations, and communications that are unique to their department and the job they are doing. That’s local scope. Those water-cooler talks aren’t supposed to get back to the CEO (probably for good reason). But also every tiny detail of each piece of each team being up to the CEO would be too much. That information belongs to that sub-team. The CEO lives in the global scope and each sub-team lives in their own local scope. They still answer to the CEO but also converse and communicate within their team to get the job done effectively and keep the company moving. That’s scope!

让我们使用现实世界中的示例来帮助我们了解其工作原理。 在任何办公室或工作场所中,都有一个从头开始的层次结构,从首席执行官开始工作,一直到入门级员工为止。 假设首席执行官拥有有关公司的所有信息,然后是管理团队,团队负责人和入门级员工。 但是,每个子团队都有自己的行话,对话和通讯,这对于他们的部门和所做的工作而言是独一无二的。 那是本地范围。 那些冷水机的谈话不应该回到首席执行官那里(可能有充分的理由)。 但是,每个团队的每个细节都取决于首席执行官。 该信息属于该子团队。 CEO居住在全球范围内,每个子团队居住在自己的本地范围内。 他们仍然对首席执行官负责,但在团队中进行交谈和沟通以有效完成工作并保持公司运转。 那是范围!

Scope如何在JavaScript中工作? (How does Scope work in JavaScript?)

Every piece of JavaScript code is run in an execution context. The execution context refers to the environment in which the code is being fired off. In a JavaScript execution context, we can see to all of the variables and functions that were declared within that context. We can have both a global execution context and a local execution context for our code, still following the principles of where the code was defined discussed above (inside or outside a block of code).

每段JavaScript代码都在执行上下文中运行。 执行上下文是指在其中触发代码的环境。 在JavaScript执行上下文中,我们可以看到在该上下文中声明的所有变量和函数。 我们可以同时具有代码的全局执行上下文和本地执行上下文,但仍要遵循上面讨论的代码定义原理(在代码块内部或外部)。

全球范围 (Global Scope)

Variables and functions declared in the global scope are available everywhere in your JavaScript code. These variables must be defined outside of a function or block of code. All scripts and functions on a web page can access these variables.

全局范围中声明的变量和函数在您JavaScript代码中随处可见。 这些变量必须在函数或代码块之外定义。 网页上的所有脚本和功能都可以访问这些变量。

let dogName = "Rover";
nameMyDog();function nameMyDog() {
document.getElementById("dog-name").innerHTML = "Your name is " + dogName;
}

Both the variable dogName and the function nameMyDog were declared in the global scope and therefore, we have access to both everywhere in the subsequent code.

变量dogName和函数nameMyDog都是在全局范围内声明的,因此,我们可以在后续代码中的任何地方访问它们。

Variables created without a const, let, or var keyword are always globally-scoped. Even if it’s in a block or inside a function is is available everywhere!

不带constletvar关键字创建的变量始终是全局范围的 即使在块中或内部,函数无处不在!

While it’s nice to have all that information available to us everywhere sometimes, it’s not best practice to declare loads of globally scoped variables and functions as it can lead to some hairy debugging problems down the line. So try your best to keep your scopes small and specific.

尽管有时在所有地方都可以使用所有这些信息是很不错的,但最好不要声明全局范围的变量和函数,因为它可能导致一些麻烦的调试问题。 因此,请尽最大努力使示波器小而有针对性。

Pride Rock Gif
Source 资源

Global scope is kind of like that scene in the Lion King where Mufasa asks Simba to look at their kingdom. Everything the light touches is that Global scope.

全球范围有点像狮子王中的场景,穆法萨(Mufasa)要求辛巴(Simba)看看他们的王国。 触及的一切都是全球范围。

当地范围 (Local Scope)

Variables defined inside a block of code or function are in local scope. They have a different scope for every call of that function. This means that variables having the same name can be used in different functions because those variables are tied to their respective functions and have different scopes, and are not available in other functions.

在代码或函数块中定义的变量在本地范围内。 对于该函数的每次调用,它们具有不同的作用域。 这意味着具有相同名称的变量可以在不同的函数中使用,因为这些变量绑定到它们各自的函数并且具有不同的作用域,并且在其他函数中不可用。

// Global Scope
function startsLocalScopeFunction() {
// Local Scope #1
function newLocalScopeFunction() {
// Local Scope #2
}
}
// Global Scope
function AnotherLocalFunction() {
// Local Scope #3
}
// Global Scope

定义范围链 (Define a Scope Chain)

All the functions/variables you write will have access to the scope chain. Think of the scope chain as an upside-down pyramid of information. If the point of the pyramid was a Javascript function, it would have access to each outer layer or scope of the pyramid of functions. When things(functions/variables) are declared in Javascript, Javascript with attempt to locate the value of those things in the current scope searching layer after layer of the pyramid (outer scope) until it finds the information it’s looking for or reaches the global scope. If it is unable to find the thing it’s looking for it will either implicitly declare it (if not in strict mode)or it will throw and error.

您编写的所有函数/变量都可以访问作用域链 。 将范围链视为信息的颠倒金字塔。 如果金字塔的点是Javascript函数,它将可以访问函数金字塔的每个外层或范围。 当使用Javascript声明事物(函数/变量)时,Javascript尝试在当前范围的金字塔(外部范围)的下一层搜索当前范围中找到这些事物的值,直到找到要查找的信息或到达全局范围。 如果找不到它正在寻找的东西,它将隐式声明它(如果不是在严格模式下),否则将抛出错误。

词汇范围 (Lexical Scoping)

In Javascript, every time a function is declared it makes it’s own scope, like we talked about in local scope.

在Javascript中,每次声明一个函数都会使其成为自己的作用域,就像我们在本地作用域中所讨论的那样。

The lexing phase determines how all variables and identifiers that are declared and how they will be looked up. For example let dog = 'Rover' is two separate steps in lexing time:

词法检查阶段确定如何声明所有变量和标识符以及如何查找它们。 例如, let dog = 'Rover'是词法化时间的两个独立步骤:

  1. let dog declares the variable in the scope before code execution.

    let dog在代码执行之前在范围内声明变量。

  2. Dog = 'Rover' assigns the value 'Rover' to the variable dog, if it is found in the available scope.

    Dog = 'Rover'将值'Rover'到可变dog ,如果在可用的范围中。

The most important factor is where a variable is declared!

最重要的因素是声明变量的位置!

Example 1:

范例1:

var imNormalconsole.log('imNormal:', imNormal); // imNormal: 1

Example 2:

范例2:

console.log('imDeclared:', imDeclared); // imDeclared: undefinedvar imDeclared

Example 3:

范例3:

console.log('imNotDeclared:', imNotDeclared); // Uncaught ReferenceError: a is not defined

console.log('imNotDeclared:', imNotDeclared); // Uncaught ReferenceError: a is not defined

Example 1 works as you would expect it too, however note the differences between other two examples. Example 2 logs undefined for imDeclared, but the identifier imDeclared has itself been declared; compared with example 3 in which the identifier imNotDeclared was not declared, thus resulting in a reference error.

示例1也可以按您期望的方式工作,但是请注意其他两个示例之间的差异。 示例2记录了未定义的imDeclared日志,但是标识符imDeclared本身已经被声明; 与其中未声明标识符imNotDeclared示例3进行比较,从而导致引用错误。

Scope is not defined at runtime, rather it can be accessed at runtime.

范围不是在运行时定义的,而是可以在运行时访问的。

回顾 (Recap)

Scope in Javascript helps us to understand where the information is stored. It allows us to understand where our variables and functions are visible and accessible within our code.

Javascript的作用域可帮助我们了解信息的存储位置。 它使我们能够了解变量和函数在代码中可见和可访问的位置。

JavaScript uses lexical scope which means that scope of variables is determined at compile time. Understanding lexing time and the Scope chain can help us to write clean, efficient code that does not reuse or confuse data.

JavaScript使用词法作用域,这意味着变量的作用域在编译时确定。 了解词法处理时间和作用域链可以帮助我们编写干净,高效的代码,而不会重用或混淆数据。

Scope Chain

范围链

Scope

范围

Scope and Scope Chain

范围和范围链

翻译自: https://medium.com/weekly-webtips/javascripts-scope-b26811752f3c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值