Parsing JavaScript scopes and scope chains (with examples)
The content this article brings to you is about the analysis of JavaScript scope and scope chain (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
JavaScript has a feature called scope. Although the concept of scope is not easy to understand for many novice developers, in this article I will try my best to explain scope and scope chain in the simplest way possible. I hope everyone will learn something!
Scope
1. What is scope
Scope is the visibility of variables, functions and objects in certain specific parts of the runtime code. Accessibility. In other words, scope determines the visibility of variables and other resources within a block of code. Maybe these two sentences are not easy to understand. Let's take a look at an example first:
function outFun2() { var inVariable = "内层变量2"; } outFun2();//要先执行这个函数,否则根本不知道里面是啥 console.log(inVariable); // Uncaught ReferenceError: inVariable is not defined
From the above example, you can understand the concept of scope. The variable inVariable is not declared in the global scope, so it is in the global scope. An error will be reported if the value is retrieved. We can understand it this way: The scope is an independent territory, so that the variables will not be leaked or exposed. In other words, the biggest use of scope is to isolate variables. Variables with the same name in different scopes will not conflict.
Before ES6, JavaScript did not have block-level scope, only global scope and function scope. The arrival of ES6 provides us with ‘block-level scope’, which can be reflected by the new commands let and const.
2. Global scope and function scope
Objects that can be accessed anywhere in the code have global scope. Generally speaking, the following situations have global scope:
- The outermost function and variables defined outside the outermost function have global scope
var outVariable = "我是最外层变量"; //最外层变量 function outFun() { //最外层函数 var inVariable = "内层变量"; function innerFun() { //内层函数 console.log(inVariable); } innerFun(); } console.log(outVariable); //我是最外层变量 outFun(); //内层变量 console.log(inVariable); //inVariable is not defined innerFun(); //innerFun is not defined
- All variables that are not defined and directly assigned a value are automatically declared as owned Global scope
function outFun2() { variable = "未定义直接赋值的变量"; var inVariable2 = "内层变量2"; } outFun2();//要先执行这个函数,否则根本不知道里面是啥 console.log(variable); //未定义直接赋值的变量 console.log(inVariable2); //inVariable2 is not defined
- All properties of window objects have global scope
Generally, the built-in properties of window objects have global scope, for example window.name, window.location, window.top, etc.
The global scope has a drawback: if we write many lines of JS code and the variable definitions are not included in functions, then they will all be in the global scope. This will pollute the global namespace and easily cause naming conflicts.
// 张三写的代码中 var data = {a: 100} // 李四写的代码中 var data = {x: true}
This is why the source code of libraries such as jQuery and Zepto will be placed in (function(){....})()
. Because all variables placed inside will not be leaked or exposed, will not be polluted to the outside, and will not affect other libraries or JS scripts. This is a manifestation of function scope.
Function scope refers to variables declared inside a function. Contrary to the global scope, the local scope is generally only accessible within a fixed code fragment, most commonly within a function.
function doSomething(){ var blogName="浪里行舟"; function innerSay(){ alert(blogName); } innerSay(); } alert(blogName); //脚本错误 innerSay(); //脚本错误
Scopes are hierarchical. The inner scope can access variables in the outer scope, but not vice versa. Let’s look at an example. It may be easier to understand using bubbles as a metaphor for scope:
The final output result is 2, 4, 12
- Bubble 1 is the global scope, with the identifier foo;
- Bubble 2 is the scope foo, with the identifiers a, bar, b;
- Bubble 3 is the scope bar , only identifier c.
It is worth noting: Block statements (statements between curly brackets "{}"), such as if and switch conditional statements or for and while loop statements, unlike functions, they do not A new scope will be created. Variables defined within a block statement will remain in the scope in which they already exist.
if (true) { // 'if' 条件语句块不会创建一个新的作用域 var name = 'Hammad'; // name 依然在全局作用域中 } console.log(name); // logs 'Hammad'
Beginners to JS often need some time to get used to variable hoisting, and if they don't understand this unique behavior, it may lead to
bugs. Because of this, ES6 introduced block-level scope to make the life cycle of variables more controllable.
3. Block-level scope
Block-level scope can be declared through the new commands let and const. The declared variables cannot be accessed outside the scope of the specified block. Block-level scope is created in the following situations:
- Within a function
- Within a block of code (surrounded by a pair of curly braces)
- Declared variables will not be promoted to the top of the code block
function getValue(condition) { if (condition) { let value = "blue"; return value; } else { // value 在此处不可用 return null; } // value 在此处不可用 }
- Duplicate declarations are prohibited
var count = 30; let count = 40; // Uncaught SyntaxError: Identifier 'count' has already been declared
在本例中, count 变量被声明了两次:一次使用 var ,另一次使用 let 。因为 let 不能在同一作用域内重复声明一个已有标识符,此处的 let 声明就会抛出错误。但如果在嵌套的作用域内使用 let 声明一个同名的新变量,则不会抛出错误。
var count = 30; // 不会抛出错误 if (condition) { let count = 40; // 其他代码 }
- 循环中的绑定块作用域的妙用
开发者可能最希望实现for循环的块级作用域了,因为可以把声明的计数器变量限制在循环内,例如,以下代码在 JS 经常见到:
<button>测试1</button> <button>测试2</button> <button>测试3</button> <script> var btns = document.getElementsByTagName('button') for (var i = 0; i < btns.length; i++) { btns[i].onclick = function () { console.log('第' + (i + 1) + '个') } } </script>
我们要实现这样的一个需求: 点击某个按钮, 提示"点击的是第n个按钮",此处我们先不考虑事件代理,万万没想到,点击任意一个按钮,后台都是弹出“第四个”,这是因为i是全局变量,执行到点击事件时,此时i的值为3。那该如何修改,最简单的是用let声明i
for (let i = 0; i <h2 id="作用域链">作用域链</h2><h3 id="什么是自由变量">1.什么是自由变量</h3><p>首先认识一下什么叫做 <strong>自由变量</strong> 。如下代码中,<code>console.log(a)</code>要得到a变量,但是在当前的作用域中没有定义a(可对比一下b)。当前作用域没有定义的变量,这成为 自由变量 。自由变量的值如何得到 —— 向父级作用域寻找(注意:这种说法并不严谨,下文会重点解释)。</p><pre class="brush:php;toolbar:false">var a = 100 function fn() { var b = 200 console.log(a) // 这里的a在这里就是一个自由变量 console.log(b) } fn()
2.什么是作用域链
如果父级也没呢?再一层一层向上寻找,直到找到全局作用域还是没找到,就宣布放弃。这种一层一层的关系,就是 作用域链 。
var a = 100 function F1() { var b = 200 function F2() { var c = 300 console.log(a) // 自由变量,顺作用域链向父作用域找 console.log(b) // 自由变量,顺作用域链向父作用域找 console.log(c) // 本作用域的变量 } F2() } F1()
3.关于自由变量的取值
关于自由变量的值,上文提到要到父作用域中取,其实有时候这种解释会产生歧义。
var x = 10 function fn() { console.log(x) } function show(f) { var x = 20 (function() { f() //10,而不是20 })() } show(fn)
在fn函数中,取自由变量x的值时,要到哪个作用域中取?——要到创建fn函数的那个作用域中取,无论fn函数将在哪里调用。
所以,不要在用以上说法了。相比而言,用这句话描述会更加贴切:**要到创建这个函数的那个域”。
作用域中取值,这里强调的是“创建”,而不是“调用”**,切记切记——其实这就是所谓的"静态作用域"
var a = 10 function fn() { var b = 20 function bar() { console.log(a + b) //30 } return bar } var x = fn(), b = 200 x() //bar()
fn()返回的是bar函数,赋值给x。执行x(),即执行bar函数代码。取b的值时,直接在fn作用域取出。取a的值时,试图在fn作用域取,但是取不到,只能转向创建fn的那个作用域中去查找,结果找到了,所以最后的结果是30
作用域与执行上下文
许多开发人员经常混淆作用域和执行上下文的概念,误认为它们是相同的概念,但事实并非如此。
我们知道JavaScript属于解释型语言,JavaScript的执行分为:解释和执行两个阶段,这两个阶段所做的事并不一样:
解释阶段:
- 词法分析
- 语法分析
- 作用域规则确定
执行阶段:
- 创建执行上下文
- 执行函数代码
- 垃圾回收
JavaScript解释阶段便会确定作用域规则,因此作用域在函数定义时就已经确定了,而不是在函数调用时确定,但是执行上下文是函数执行之前创建的。执行上下文最明显的就是this的指向是执行时确定的。而作用域访问的变量是编写代码的结构确定的。
作用域和执行上下文之间最大的区别是:
执行上下文在运行时确定,随时可能改变;作用域在定义时就确定,并且不会改变。
一个作用域下可能包含若干个上下文环境。有可能从来没有过上下文环境(函数从来就没有被调用过);有可能有过,现在函数被调用完毕后,上下文环境被销毁了;有可能同时存在一个或多个(闭包)。同一个作用域下,不同的调用会产生不同的执行上下文环境,继而产生不同的变量的值。
The above is the detailed content of Parsing JavaScript scopes and scope chains (with examples). For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools