search
HomeWeb Front-endJS TutorialDetailed example of scope chain in JavaScript

Detailed example of scope chain in JavaScript

Nov 01, 2017 am 10:13 AM
javascriptjsScope

ReviewScope

We talked about scope in the previous section: it refers to the range that a variable can access. It stipulates How to find variables and determine the access rights of the currently executing code to the variables; also speaking of static scope is the lexical scope, which determines the reference of the variable during the compilation phase (defined by the program The position is determined, regardless of the order of code execution, and is parsed in a nested manner).

condensed question

var x=10;
    function run(){
        var name='Joel';
        console.log(x+name);//10Joel  这里做了隐适转换 当有+时有一个为string 那么会当做字符拼接来处理
    }
    run();

As shown in the above code, when executing the run function, there is a name variable in the run scope, but there is no variable x, so why is no error reported? , how is the variable x accessed? Some people may understand that it is to look for variables in the parent function scope . In fact, there is ambiguity in understanding the scope this way (if you understand that you are calling the parent function of the function, then it is definitely wrong. The following code), In the previous section, we said that the scope of javascript is a static scope, that is, should care about the location of the code definition rather than the location of the call (lexical scope) ;

var x=10;
    function fn(){
        console.log(x);
    }
    function show(f){
        var x=20;
        (function(){
            f()
        }());
    }
    show(fn);//10 并不是20

Leading out the scope chain

Understand the scope chain by analyzing the variable resolution of the scope

var a=10;
    function run(){
        var name='Joel';
        function say(){
            var content='hello';
            console.log(content+name+','+a);
        }
        say();
    }
    run();//helloJoel,10

From the previous article, we know that js scope has global scope and function scope, so the scope of the above code is as follows:

Global scope: There are variable a, run function references, and of course other functions. , Attributes (the built-in ones will not be discussed);

run function scope: variable name exists, say function reference;

say function scope: variable content exists ;

When the code is executed to console.log(content+name+','+a); First, look for the variables content, name, and a in the say function scope. If found, stop. If not found, go to the top. Search in a scope, and so on until the window global scope. If the variable a is not found in the current say scope, search in the run scope. If it is not found, search in the global scope. If it still cannot be found, It will report an error "is not defined" because the global scope is the outermost scope;

Continue to look at the following code. After we define the variable name in the say function, the name value is no longer the value in the run scope. , because the variable name is found in the say scope, it will not continue to search.

<script>
    var a=10;
    function run(){
        var name=&#39;Joel&#39;;
        function say(){
            var content=&#39;hello&#39;,name=&#39; Word&#39;;

            console.log(content+name+&#39;,&#39;+a);
        }
        say();
    }
    run();//hello Word,10
</script>

Such a step-by-step process of finding variables is called identifier parsing or you can understand it as variable parsing, then provide This line or the mechanism for finding variables in this way is called a scope chain;

Let’s summarize this process:

The first step is to find the variable in the current scope, if there is one, then Get and stop. If not, continue to search for the previous scope;

The second step, if the current scope is the global scope, it means the variable is undefined, end; otherwise, continue;

The third step, (Not the global scope, that is the function scope) Continue with the first step;

So what exactly is the scope chain?

In fact, the scope chain is essentially a linked list of pointers pointing to variable objects. It only references but does not actually contain the value of the variable object;

The scope chain structure of the above code is similar to this:

This article only introduces the scope chain. The next article officially starts to talk about the execution environment, which will involve variable objects, active objects, scope chains, etc., so as to go into the creation of the scope chain. process.

The reason why we need to write the execution environment first is because the complete scope chain is built in the execution environment.

The above is the detailed content of Detailed example of scope chain in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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
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.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),