


Understand Javascript_15_scope allocation and variable access rules, and then send a closure_javascript skills
In ECMAScript, functions are also objects. Function objects are created from a function declaration during variable instantiation, or when a function expression is evaluated or the Function constructor is called. (For information on 'function objects', please see "Understanding Javascript_08_Function Objects"). Every function object has an internal [[scope]] property, which is also composed of a list (chain) of objects. The internal [[scope]] attribute refers to the scope chain of the execution environment in which they were created, and the active objects of the current execution environment are added to the top of the object list. When we access a variable inside a function, it is actually the process of finding the variable on the scope chain.
It’s too theoretical (summarizing it to death!), let’s take a look at a piece of code:
The following figure clearly shows the memory allocation and scope allocation of the above code:

Let’s explain it below:
1. Load the code and create a global execution environment. At this time, the outer variable will be added to the variable object (window), which points to the function object. outer, at this time there is only the window object in the scope chain.
2. Execute the code. When the program executes outer(), it will look for the outer variable in the global object and call it successfully.
3. Create the execution environment of outer. At this time, a new active object will be created, add variable i, set the value to 10, add variable inner, point to the function object inner. And push the active object into the scope chain. And point the [[scope]] attribute of the function object outer to the active object outer. At this time, the scope chain is outer's active object window.
4. Execute the code and successfully assign a value to i. When the program executes inner(), it will look for the inner variable in [[scope]] of the function object outer. Called successfully after finding.
5. Create the execution environment of inner, create a new active object, add variable j, assign the value to 100, and push the active object into the scope chain, and point the [[scope]] attribute of the function object inner to the active object inner. At this time, the scope chain is: inner's active object and outer's active object global object.
6. The execution code assigns a value to j. When accessing i and j, the corresponding value is successfully found in the scope and output, and When accessing the variable adf, it was not found in the scope and an access error occurred.
Note: Through the memory graph, we will find that the scope chain and the prototype chain are so similar. This explains a lot of problems... (Be benevolent and wise, find out the answer for yourself!)
Principle of Closure
After we understand the problem of scope, the problem of closure is already very simple . What is a closure? A closure is an inner function that encloses the variables in the scope of the outer function.
Let’s look at a typical closure application: generate increment value
The outer anonymous function returns an inline function, and the inline function uses the local variable id of the outer anonymous function. Logically speaking, the local variables of the outer anonymous function go out of scope when returned, so the increment() call cannot be used. This is closure, that is, the function call returns an embedded function, and the embedded function refers to the local variables, parameters and other resources of the external function that should be closed (Close). What's going on? Let's find the answer:

According to the understanding of Scope Chain, it can be explained that the returned inline function already holds the Scope Chain when it was constructed, although outer returns cause these objects to go out of scope. lifetime scope, but JavaScript uses automatic garbage collection to release object memory: it is checked periodically according to the rules and the object is released only if it does not have any references. So the above code runs correctly.
Reference:
http://www.cnblogs.com/RicCC/archive/2008/02/15/JavaScript-Object-Model-Execution-Model.html
http://www .cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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.

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

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

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
