当前位置:网站首页>JS precompile - Variable - scope - closure
JS precompile - Variable - scope - closure
2022-06-26 07:58:00 【Small slag bright】
js Stack and heap of
- Stack : Stored are values of simple data types , And the address of complex data ( That is, the execution environment )
- Pile up : Stored are values of complex data types , This is stored in the stack first ( Keep an address ), This address points to the values in the heap !
Storage of complex objects

js Precompilation
- precompile : Is in the js Before it is actually parsed ,js The parsing engine will first preprocess the entire file ;
- var Declared variables have variable promotion !
The first question is
console.log(a)
var a = 10
console.log(a)
function a() {
console.log(a)
}
a()
// analysis :
// js Pre analysis of , Yes var Declared variable promotion , There is no assignment to it , Implement function promotion for functions first , But no function is called
// var a; underfined
// a = f a() { console.log(a) }
// console.log(a) -> f a() { console.log(a) }
// a = 10;
// console.log(a) -> 10
// a(); -> a be equal to 10 了 Instead of functions !
// result :
// ƒ a() {
// console.log(a);
// }
// a is not a function
The second question is
eg1:
a()
var a = 10
function a() {
console.log(1)
}
a()
// var a;
// a = f a () { console.log(1) }
// a()
// a = 10
// a();
// result : 1 a is not a function
eg2:
console.log(num)
var num = 10 // result undefined

Variable
- Global variables : Life cycle ( permanent ) Accessibility ( Can be accessed anywhere )
- local variable : Life cycle ( Delete immediately after function execution ) Accessibility ( Can only be accessed inside a function )
- Free variable : Life cycle ( permanent ) Accessibility ( Access... Only inside functions );
- In the case of closures, a special variable is generated
Global variables
- Global variable declaration method
- var Variables defined
- Not used var Variables defined ( Not used let、const)
- window.XXX Statement
<template>
<div>Home</div>
</template>
<script>
export default {
name: 'Home',
components: {
},
data() {
return {
msg: '1111'
}
},
created() {
this.init()
},
methods: {
init() {
var num = 10 // Global variables
// test = 'test'
window.b = 'bbb'
console.log('init', num)
function bbb() {
console.log('bbb function ', num, 'b', b)
}
bbb()
// result init 10 ; bbb function 10 b bbb
}
}
}
</script>
local variable
- Is the variable declared in the function body
- When a function is called, an execution environment will be generated , This variable is declared as a local scope in the current environment , Can only be accessed within this scope , At the end of function execution , The variable is destroyed !
var a = 10 // Global variables
function test() {
var b = 20 // local variable
console.log('b', b, 'a', a)
}
test()
console.log('b', b)
// result :b 20 a 10 ; b is not defined( because b Variables declared in a function are local variables , I can't get outside )
Free variable
- effect :
- 01: Called at any time , Will not be destroyed !
- 02: Ensure data privacy => Only your function can use ;
let a = 10 // Global variables
function test() {
let b = 20
console.log(' Free variable ', b + a) // Free variable 30
}
test()
// Free variable : It refers to the external variables inside the function ,
Scope
Global scope
- That is, the declared variables are attached to
windowOn the object ,The global scope is window object
Local scope
- After the function call , An execution environment ,
A local scope is the currently generated execution environment
Scope chain
- Comprehensiveness : If your internal function doesn't define variables , Then it will go out to the outer layer to find this variable , Until you find window here , If it were not so , It outputs undefined
- General : Finding variable paths is a scope chain , Find variables according to the principle of proximity , First, I will search from my own area , If you have, you can directly use your own variables , It does not look up one level , Stop searching until you find the position of the variable , If there is no overall situation , Find this variable , That would be a mistake , This variable is not defined
Closure
- If the variables of the external function are used in the internal function , It's a closure , Closures retain references to external environments
- If the inner function is returned outside the outer function , After the execution of the external function , You can still use the values in the closure
- Closure formation : Use variables of external functions in internal functions , It's a closure , Closure is an extension of the current scope !
Closure formation
eg1:
// test External function bbb Internal function
function test() {
var a = 100
// bbb The function uses a Variable -> It forms a closure
function bbb() {
console.log('bbb function ', a)
}
bbb()
}
test()
eg2:
function test() {
// bbb The function uses a Variable -> It forms a closure
function bbb() {
console.log('bbb function ', bbb)
}
bbb()
}
test()
// analysis :
// test call :
// test Execution environment ( Pre parse ) bbb = function
// bbb call Output bbb For a function
Maintenance of closures
- The above closures produce , After the function call is executed , The variables inside will still be destroyed , To maintain the persistence of the current variable , You need to return a function on the inner function ( This function uses the variables of an external function )
function test() {
// bbb The function uses a Variable -> It forms a closure
var num = 0
function bbb() {
console.log('bbb function ', num++) // To form a closure
}
return bbb
}
var demo = test()
console.log('demo', demo)
demo()
demo()
// analysis
// test Call to :
// test execution environment { num:underfined, bbb:fun }
// At present test function The return is bbb function
// Then on test assignment A function bbb function log Output f bbb(){}
// call demo Equivalent to bbb() -> log Priority output num The value is 0 And then add
// Then call demo() -> log Priority output num The value is 1 And then add
// result
// demo ƒ bbb()
// 0 1
The function of closures
demand : Click on ul Medium li, Output the corresponding index number
// demand : Using closures , To click on the current small li Get the current small li The index number of
var lis = document.querySelectorAll("li");
for (var i = 0; i < lis.length; i++) {
// Using closures , Put the current i As a parameter, it is passed into the immediate execution function , Before starting the current click event , Print the corresponding index number !
(function (num) {
lis[i].onclick = function () {
console.log(num);
}
})(i)
}
The throttle function of closure
// demand : Using closures , Encapsulate a function for throttling and anti chattering
//throttle --- throttle antiShake --- Shake proof
// Throttling package
// Parameters 1: Callback function ( What is written in it is the function of consumption performance ) Parameters 2: Delay time Parameters 3: change this The direction of !
function throttle(callback, delay, context) {
var flag = true;
delay = delay || 100;
return function () {
// Generating closures
if (flag) {
flag = false;
setTimeout(function () {
context ? callback.call(context) : callback();
flag = true;
}, 200)
}
}
}
// document.onscroll = throttle(function () {
// console.log(" Functions that consume performance ");
// }, 200)
Anti shake function of closure
// Debounce the package
// Parameters 1: Callback function Parameters 2: Delay time Parameters 3: change this The direction of
function antiShake(callback, delay, context) {
var timer = "";
var delay = delay || 100;
return function () {
// Generating closures
clearInterval(timer)
timer = setTimeout(function () {
context ? callback.call(context) : callback();
}, 200)
}
}
// document.onscroll = antiShake(function () {
// console.log(" Consuming performance 2");
// }, 200)
边栏推荐
- Area of Blue Bridge Cup 2 circle
- Jemter stress test - basic requirements - [teaching]
- Google Earth Engine(GEE) 01-中输入提示快捷键Ctrl+space无法使用的问题
- Project management learning
- Uni app is similar to Taobao in selecting multiple specifications of commodities (inventory judgment)
- Exploration and practice of incremental data Lake in station B
- What if the service in Nacos cannot be deleted?
- ECE 9203/9023 analysis
- You can command Siri without making a sound! The Chinese team of Cornell University developed the silent language recognition necklace. Chinese and English are OK
- buuresevewp
猜你喜欢

Real machine debugging of uniapp custom base

Chapter VIII (classes and objects)

Wifi-802.11 2.4G band 5g band channel frequency allocation table

我想造SQL数据(存储结构)

Chapter II (summary)

Here is the command to display the disk space usage. Go ahead and pay attention to more wonderful things!

Chapter 4 (functions and preprocessing)

Chapter 3 (data types and expressions)

Niuniu looks at the cloud (greedy, hash, push formula) - the first session of Niuke winter vacation training camp

Take you three minutes to get started typescript
随机推荐
Database learning notes II
Opencv mouse event + interface interaction drawing rectangle polygon selection ROI
Livevideostackcon | evolution of streaming media distribution for online education business
Chapter 9 (using classes and objects)
What is Wi Fi 6 (802.11ax)? Why is Wi Fi 6 important?
Automatic backup of MySQL database in the early morning with Linux
Google Earth engine (GEE) 01- the prompt shortcut ctrl+space cannot be used
Seven important reasons for responsive Web Design
Jemter stress test - basic requirements - [teaching]
Database learning notes I
1002: easy to remember phone number
[NLP] vector retrieval model landing: Bottleneck and solution!
The 9th zero code training camp is officially open for registration! (Beijing, Shanghai, Guangzhou and Shenzhen)
OSPF design principles, commands take H3C as an example
Jemter 壓力測試 -基礎請求-【教學篇】
Real machine debugging of uniapp custom base
Pycharm settings
PyTorch-12 GAN、WGAN
Chapter 4 (functions and preprocessing)
Open a file at line with'filename:line'syntax - open a file at line with'filename:line' syntax