current position:Home>Understand JavaScript function execution process and scope chain
Understand JavaScript function execution process and scope chain
2022-04-29 10:33:26【Drowned fish u】
After understanding the execution of global code and the promotion of scope , Let's next understand the more special Function execution and Scope chain .
Global code execution process of function
The code is parsed , Open up function memory space ,go Reference function address in .
Through the variable promotion of global code, we know , In the process of code parsing , Will generate global objects Global Object (GO), And define the global variables in it , Functions will also be defined during this period , And generate a memory space exclusive to the function , Access... By reference .
var name = 'mjy'
foo(123)
function foo(num) {
console.log(m)
var m = 10
var n = 20
}
// The code is parsed , The browser engine will help us create a go object
var globalObject = {
String: " class ",
Date: " class ",
seTimeount: " function ",
window: globalObject
name: undefined,
foo: 0xa00 // Function defined , And generate a function memory space in the heap , Refer to... As an address
}
In the space opened up by functions : The scope of the function scope And function executor ( Code block ), The scope is the parent scope of the current function , in other words : The scope of the function is defined in memory before the function is executed . This is an important point
Icon :
Before function execution , produce FEC,AO object ,FEC Push
When the function code executes ,js Will create a Function execution context FEC(Functional Execution Context), And put the function execution context FEC,** Add to the execution context stack ECStack(EXecution Context Stack)** in .
stay FEC The execution context of the function is in the stack , And global execution context GEC equally , There is also vo object , At this time vo Object refers to a function created by **AO(ACtivation Object)** object . Unlike the global execution context , Functional FEC There is also a scope chain in the execution context stack of the function , Its value is the current scope AO + GO
function foo(num) {
console.log(num)
var m = 20
var n = 10
}
// foo The activation object of the function AO
activationObject = {
num = undefined, // The parameters of a function are also variables defined in the function
m = undefined,
n = undefined
}
foo(123)
// When the function executes , In turn ao Object
activationObject = {
num = 123,
m = 20,
n = undefined
}
The execution of a function call
When a nested function appears in a function , In the outer function AO in , It also refers to the function by storing the reference form of the address . The schematic diagram of the function in the memory heap is like this
The process of finding variables in functions
When we look for a variable in a function , The search path is in its own FEC Along the scope chain scope chain To find out ,
The value of the scope chain is scopechain: Self scope AO + Parent scope ParaentScope
For example, the following code
var message = "hello Global"
function foo() {
console.log(message)
}
function bar() {
var message = "hello Bar"
foo()
}
bar() // The output is :hello Global
foo Functional AO There's No... in the object message Variable , At this point, it will follow the scope chain scopechain Go to the parent scope to find , and foo The parent scope of the function is foo Function opens up memory space , It's already defined , Its value is the global scope GO. So I found GO Medium message.
The resulting : The function scope is related to the definition location , It has nothing to do with the location of the call
Icon :
summary :
** Code parsing :** The function... Is defined in the code , Open up your own function space for it , The function space stores the parent scope and function body .
Before function execution ( The function will only have this step if it is to be executed ): Create function execution context FEC,AO Function active object ,AO Object stores the variables defined in the function .FEC There is VO The object points to AO, And the scope of the function scopechain, The scope chain value is AO+ The scope of the parent function in memory .
** Function execution time :** Function execution context FEC Push ECS. The code is executed in sequence , by AO Object .
** After function execution :** The function memory space opened up is destroyed , Free memory . Functional AO Object and memory space no longer exist .
If a function is nested in a function , Before the parent function runs , Let's say the parent function AO When created, it will be read , Open up new function memory space in the heap , Association through address reference method . When nested functions run , Run the top 4 step .
When we look for variables in a function : It will find... According to the scope chain of the function , Find yourself first AO object , Then go to the scope to find . The scope of the function is related to the definition position , It has nothing to do with the location of the call ( The scope of the function is defined in memory before the function is executed ).
Interview questions :
1. The scope of the function
var n = 100
function foo() {
n = 200
}
foo()
console.log(n)
2. The execution of the function
function foo() {
console.log(n)
var n = 200
console.log(n)
}
var n = 100
foo()
3. Scope chain of function
var n = 100
function foo1() {
console.log(n)
}
function foo2() {
var n = 200
console.log(n)
foo1()
}
foo2()
console.log(n)
4. The return value of the function
var a = 100
function foo() {
console.log(a)
return
var a = 200
}
foo()
5. Scope and scope chain of function and global variable
function foo() {
var a = b = 100
// amount to
// b = 100
// var a = b
}
foo()
console.log(a)
console.log(b)
Answer key :
1. Along the scope chain scopechain Find the GO The variables in the n, And assign it a value of 200
200
2. The code hasn't been executed yet ,AO Variable in object n The value of is the initial value undefined, When the assignment statement is executed ,n The value of will change .
undefined
200
3.foo1 Of AO There are no variables in object n, Remove the parent scope in the scope chain GO Search for .
foo2 in AO There are variables in the object n, And the value has been assigned before the output statement .
200
100
100
4. The return value of the function is in AO It is also defined in
200
5. Global object GO There are no variables defined in a, So the output a Report errors .
Not defined in the function b The assignment is 100, b = 100, Strictly speaking, this is a wrong Syntax , but js You're allowed to write that , It will find... Along the scope , Finally arrive GO Define a variable in b, And assign it to .
Report errors :a is not defined
100
copyright notice
author[Drowned fish u],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290915030966.html
The sidebar is recommended
- Install and configure nginx in Linux Environment
- Vue dynamically binds attributes and dynamically obtains attribute values
- Summary method of Vue value in key pair mapping
- Vue simply realizes the addition, deletion and modification of each tab page without route jump
- Vue time control common processing
- Vue validation array
- Simple and easy to let you know what AJAX is, even if you are a little white, a rookie can understand it!
- Receive the JSON string from the front end, and summarize the methods of parsing and value taking at the back end
- Solution: httpmessagenotreadableexception: JSON parse error: invalid UTF-8
- Vuetify: install vuetify from scratch
guess what you like
Install CSS from tailwind
Ubuntu 16 wireless network card model query and driver installation, Lenovo g400 bcm43142 network card WiFi
Some color knowledge to understand at the front end
Functional programming of front-end development
A front-end interview question -- implementing an encapsulated Ajax device (promise version)
Dynamic components of angular
Front end written test pit -- JS implicit conversion
Shallow understanding of HTTP
React style modification background invalid
Finding the k-th small element of ordered matrix (dichotomy idea)
Random recommended
- JavaScript functions -- pre parsing, Iife, advanced functions, recursion
- JavaScript object
- How to introduce element plus gracefully in vue3 project on demand
- Component slot Vue js
- How to write game interface style in HTML
- Ask some front-end questions.
- Information | driverless taxi has come to Beijing. Xiaoma Zhixing has been approved to carry out automatic driving service in Beijing
- [taro react] - H5 route configuration cancels # on the route
- Reverse advanced, using ast technology to restore JavaScript obfuscated code
- JavaScript object
- Vue introduces vant / elementul
- JavaScript queue“
- Vue content summary
- vue3. 0
- Small tips: detection of JS font loading failure or completion
- CSS is a box that has been climbing
- Leetcode215 - the kth largest element in the array - quick sort - quick select - template
- CSS adds effect to the four corners of div
- HTTP error 500.19 internal server error occurred in the integration pageoffice of aspnetcore project,
- Front end < TD > what is the word limit of the label
- Construction and development of automatic test platform based on HTTP runner
- Application of RT thread - use RT thread on stm32l051 (v. conclusion of wireless temperature and humidity sensor)
- Expose Dubbo to HTTP service
- Put the front end into the spring cloud project
- Front end learning day 4 - CSS
- Vue URL jump page with parameters
- JavaScript Chapter 13 traversal of arrays and implicit parameters of function methods
- These CSS efficiency improvement skills, you need to know!
- Beijing has opened the pilot of unmanned operation of passenger cars, and the driverless air outlet has arrived
- Test theory series - Test Case elements and design methods Part II
- How to make the peak value of measured output voltage not less than 2V
- Hexo quickly set up its own blog
- Gee synthetic cloudless landsat-8 and sentry-2 data
- Prototype object creation method case JavaScript specific implementation steps
- YAF CLI and HTTP access modes
- Simple HTML + CSS animation web page production DW simple animation web page production
- The correct way for web programmers to make a pink girl series happy birthday blessing web page (HTML + CSS + JS)
- HTML + CSS + JS to make simple animation web pages
- HTML gourmet web page production DW static web page production div + CSS gourmet web page implementation and production
- Programmer 520 Tanabata Valentine's Day confession code HTML + JS + CSS petal photo album web page template programmer confession necessary