search
HomeWeb Front-endFront-end Q&AScope chain, the underlying principle of JavaScript (detailed explanation with pictures and text)

This article brings you knowledge about scope chain in JavaScript. External space cannot access internal variables. We often only know this basic rule. So what is the basic underlying principle to implement this basic rule? Hope it can give you some help!

Scope chain, the underlying principle of JavaScript (detailed explanation with pictures and text)

Scope

1. What is scope

Simply put, scope (English: scope) is a set of rules for finding variables based on their names. The scope can be generally understood as a closed space. This space is closed and does not It will have an impact on the outside. The outside space cannot access the inside space, but the inside space can access the outside space that wraps it.

2.[[Scopes]]Attributes

In javascript, each function is an object, and there are some properties in the object that we It can be accessed, but some of them are not freely accessible to us. The [[Scopes]] attribute is one of them. This attribute can only be read by the JavaScript engine.

In fact, [[scope]] is what we often call scope, which stores the context collection of the scope runtime.

Here because func.prototype.constructor and func point to the same function, so here we view the [[Scopes]] attribute by accessing the prototype object of the function func

Scope chain, the underlying principle of JavaScript (detailed explanation with pictures and text)

3. Scope chain

#The collection of execution-time context objects stored in [[scope]], this collection is connected in a chain , we call this chain connection a scope chain. JavaScript searches for variables through the scope chain. The search method is to query downwards along the top of the scope chain (in which function the object is found inside, it is searched in the function scope chain)

4. Illustration of the principle of finding variables

//以如下代码为例说明JavaScript通过作用域链查找变量的原理**
function a() {
  function b() {
      var b = 123;
  }
  var a = 123;
  b();
}
var glob = 100;

1. When the global function a() is defined, the scope chain is as follows

Scope chain, the underlying principle of JavaScript (detailed explanation with pictures and text)

The [[Scopes]] attribute of the function points to the scope chain object. At this time, the scope chain has only one key-value pair, and this key-value pair points to the global Object, the global object stores things that can be accessed globally, that is, the outermost scope, which everyone can access.

2. When the global function a() is activated and called, the scope chain is as follows

Scope chain, the underlying principle of JavaScript (detailed explanation with pictures and text)

At this time, the first thing that the scope chain can access is the key-value pair in the Activation Object. If not, the global object will be accessed

3. When function b is defined in function a() , the scope chain of b is as follows

Scope chain, the underlying principle of JavaScript (detailed explanation with pictures and text)

When b is only defined but not called, the scope chain of b is the same as a

4. When function b in function a() is activated and called, the scope chain is as follows

Scope chain, the underlying principle of JavaScript (detailed explanation with pictures and text)

The scope chain first points to the Activation Object of function b(). The search variables are also accessed in the order of the scope chain. Stop when found

5. Summary

The reason why the external scope cannot access the internal scope is that the scope chain of the external scope does not have the Activation Object of the internal scope, so internal variables cannot be accessed. The order of accessing variables in the internal scope is according to the scope. Chain, first search from the inside, if not, look outward along the scope chain, the outside is the global scope

Related recommendations:javascript learning tutorial

The above is the detailed content of Scope chain, the underlying principle of JavaScript (detailed explanation with pictures and text). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
Understanding useState(): A Comprehensive Guide to React State ManagementUnderstanding useState(): A Comprehensive Guide to React State ManagementApr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

What are the advantages of using React?What are the advantages of using React?Apr 25, 2025 am 12:16 AM

Reactispopularduetoitscomponent-basedarchitecture,VirtualDOM,richecosystem,anddeclarativenature.1)Component-basedarchitectureallowsforreusableUIpieces,improvingmodularityandmaintainability.2)TheVirtualDOMenhancesperformancebyefficientlyupdatingtheUI.

Debugging in React: Identifying and Resolving Common IssuesDebugging in React: Identifying and Resolving Common IssuesApr 25, 2025 am 12:09 AM

TodebugReactapplicationseffectively,usethesestrategies:1)AddresspropdrillingwithContextAPIorRedux.2)HandleasynchronousoperationswithuseStateanduseEffect,usingAbortControllertopreventraceconditions.3)OptimizeperformancewithuseMemoanduseCallbacktoavoid

What is useState() in React?What is useState() in React?Apr 25, 2025 am 12:08 AM

useState()inReactallowsstatemanagementinfunctionalcomponents.1)Itsimplifiesstatemanagement,makingcodemoreconcise.2)UsetheprevCountfunctiontoupdatestatebasedonitspreviousvalue,avoidingstalestateissues.3)UseuseMemooruseCallbackforperformanceoptimizatio

useState() vs. useReducer(): Choosing the Right Hook for Your State NeedsuseState() vs. useReducer(): Choosing the Right Hook for Your State NeedsApr 24, 2025 pm 05:13 PM

ChooseuseState()forsimple,independentstatevariables;useuseReducer()forcomplexstatelogicorwhenstatedependsonpreviousstate.1)useState()isidealforsimpleupdatesliketogglingabooleanorupdatingacounter.2)useReducer()isbetterformanagingmultiplesub-valuesorac

Managing State with useState(): A Practical TutorialManaging State with useState(): A Practical TutorialApr 24, 2025 pm 05:05 PM

useState is superior to class components and other state management solutions because it simplifies state management, makes the code clearer, more readable, and is consistent with React's declarative nature. 1) useState allows the state variable to be declared directly in the function component, 2) it remembers the state during re-rendering through the hook mechanism, 3) use useState to utilize React optimizations such as memorization to improve performance, 4) But it should be noted that it can only be called on the top level of the component or in custom hooks, avoiding use in loops, conditions or nested functions.

When to Use useState() and When to Consider Alternative State Management SolutionsWhen to Use useState() and When to Consider Alternative State Management SolutionsApr 24, 2025 pm 04:49 PM

UseuseState()forlocalcomponentstatemanagement;consideralternativesforglobalstate,complexlogic,orperformanceissues.1)useState()isidealforsimple,localstate.2)UseglobalstatesolutionslikeReduxorContextforsharedstate.3)OptforReduxToolkitorMobXforcomplexst

React's Reusable Components: Enhancing Code Maintainability and EfficiencyReact's Reusable Components: Enhancing Code Maintainability and EfficiencyApr 24, 2025 pm 04:45 PM

ReusablecomponentsinReactenhancecodemaintainabilityandefficiencybyallowingdeveloperstousethesamecomponentacrossdifferentpartsofanapplicationorprojects.1)Theyreduceredundancyandsimplifyupdates.2)Theyensureconsistencyinuserexperience.3)Theyrequireoptim

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor