search
HomeWeb Front-endJS TutorialScope chains and closures in JavaScript

Scope chains and closures in JavaScript

Nov 26, 2016 pm 01:11 PM
javascript

• Scope
o Global scope
o Local scope
• Scope chain
• Execution context
• Active object
• Closure
• Closure optimization
There is a concept in JavaScript that has not been learned before—— Closure. What is closure? From the surface understanding, it is a closed package, which is related to scope. Therefore, before talking about closures, let’s talk about scope. C



Generally speaking, the variables and functions used in a program code are not always available. The scope of its availability is the scope of action. Reliability, reducing name conflicts.
          Global Scope
        Objects that can be accessed anywhere in the code have global scope. The following situations have global scope:
    1. The outermost function and the outermost function defined outside Variables have global scope, for example:
[javascript]
1. var outSide="var outside";
2. function outFunction(){
3. var name="var inside";
4. function inSideFunction(){
5.         alert(name); ; "
3. All properties of the window object have a global scope. For example: the built-in properties of the window object have a global scope, such as window.name, window.location, window.top, etc.
Local Scope (Local Scope)
[ javascript]
1. function outFunction(){
2. var name="inside name";
3. function inFunction(){
4. alert(name ; )
                                               In JavaScript, everything in JavaScript is an object, including functions. Function objects, like other objects, have properties that can be accessed through code and a set of internal properties that are only accessible to the JavaScript engine. One of the internal properties is scope, which contains the collection of objects in the scope in which the function was created, called the function's scope chain, which determines what data can be accessed by the function.
 When a function is created, its scope chain will be filled with data objects accessible in the scope in which the function was created. For example, function:
[javascript]
1. function add(num1,num2) {
2. var sum = num1 + num2;
3. return sum;
4. }

When the function add is created, its scope A global object will be filled in the chain, which contains all global variables, as shown in the picture below (note: the picture only illustrates a part of all variables):



It can be seen that the scope chain of a function is created when the function is created.
Execution context (Execute context)
The scope of the function add will be used during execution, for example:
[javascript]
1. var total = add(5,10);

When the add function is executed, JavaScript An Execute context will be created, which contains all the information needed by the add function during runtime. Execute context also has its own Scope chain. When the function runs, the JavaScript engine will first initialize the execution context's scope chain from the scope chain using the add function.
Active Object
Then the JavaScript engine will create an Active Object. These values ​​​​are copied to the scope chain of the runtime context in the order they appear in the function. Together they form a new object—— "Activation object", this object contains all local variables, parameters and this and other variables during the function runtime. This object will be pushed to the front end of the scope chain. When the runtime context is destroyed, the activation object will also Then destroyed. The new scope chain is shown in the figure below:

Scope chains and closures in JavaScript

Execution context is a dynamic concept. It is created when the function is running. The active object Active Object is also a dynamic concept. It is referenced by the scope chain of the execution context. , it can be concluded that execution context and active objects are both dynamic concepts, and the scope chain of the execution context is initialized by the function scope chain.过 During the function execution process, every time you encounter a variable, you will retrieve where to obtain and store data from. This process starts from the domain chain head, that is, starting from the object of the activity to find the identifier of the same name. If you find it, use it. If there is no variable corresponding to this identifier, continue to search for the next object in the scope chain. If all objects are not found after searching, the identifier is considered undefined. During the execution of the function, each identifier must go through Such search process.
Closure (closure)
Let’s look at an example first, javascript code:
[javascript]
1.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.