当前位置:网站首页>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)
边栏推荐
- Detach an entity from jpa/ejb3 persistence context
- 指南针炒股软件开户是合法的吗?安全吗
- 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
- Common uniapp configurations
- [UVM practice] Chapter 2: a simple UVM verification platform (4) the ultimate masterpiece of UVM: sequence
- [UVM foundation] UVM_ Driver member variable req definition
- Yyds dry inventory executor package (executor function)
- Rewrite string() method in go language
- Cloud native integration data warehouse heavy release
- Database learning notes I
猜你喜欢

Uniapp wechat withdrawal (packaged as app)

What is Wi Fi 6 (802.11ax)? Why is Wi Fi 6 important?

QT之一个UI里边多界面切换
![[UVM basics] TLM common data receiving and sending and data receiving examples](/img/4f/6c6e8b26124ba042f949291b944c3d.jpg)
[UVM basics] TLM common data receiving and sending and data receiving examples

Uniapp uses uviewui

Baoyan postgraduate entrance examination interview - Network

Real machine debugging of uniapp custom base

The 9th zero code training camp is officially open for registration! (Beijing, Shanghai, Guangzhou and Shenzhen)
![Jemter stress test - basic requirements - [teaching]](/img/f4/36dbd80e89d96e1121a6e2b92d1d07.png)
Jemter stress test - basic requirements - [teaching]
![JMeter stress test web agent local interface test [teaching]](/img/6d/a8b3cd1ca55993fe59c066f95ef093.png)
JMeter stress test web agent local interface test [teaching]
随机推荐
Database learning notes I
[North Asia data recovery] a server data recovery method in which the partitions in the RAID5 array are formatted due to the misoperation of the NTFS file system
Double linked list -- tail interpolation construction (C language)
Apache inlong graduated as a top-level project with a million billion level data stream processing capability!
What if the service in Nacos cannot be deleted?
Automatic backup of MySQL database in the early morning with Linux
Class class of box selection four to and polygon box selection based on leaflet encapsulation
1010. song backtracking with total duration divisible by 60
Power apps application practice | easily develop employee leave attendance management applet with power apps
Opencv鼠标事件+界面交互之绘制矩形多边形选取感兴趣区域ROI
Detach an entity from jpa/ejb3 persistence context
JS Date object
Project management learning
Chapter II (summary)
The first screen time, you said you optimized it, then you calculated it and showed it to me!
What is the five levels of cultivation of MES management system
ReW_ p
信息学奥赛一本通 1355:字符串匹配问题(strs)
I want to create SQL data (storage structure)
指南针炒股软件开户是合法的吗?安全吗