当前位置:网站首页>JS advanced ES6 ~ es13 new features
JS advanced ES6 ~ es13 new features
2022-07-28 23:59:00 【Xuan Yu Shang】

Catalog
One 、ECMA New description concept
3、 ... and 、let && const and var The difference between
2. obtain symbol Corresponding key
6、 ... and 、Set data structure
02 - Use Set duplicate removal
7、 ... and 、weakSet data structure
8、 ... and 、Map data structure
Ten 、 Optional chain ?. Optional chain operator - JavaScript | MDN
1. Call directly : It's dangerous
2. Judgment call : so much trouble
One 、ECMA New description concept
ES6 Previous concepts
Execution context stack :Execution Context Stack, Stack structure for execution context
Execution context :Execution Context, The code will create the corresponding execution context before execution
The variable object :Variable Object, Contextual VO object , Used to record function and variable declarations
Global object :Global Object, Global execution context sensitive VO object
Activate the object :Activation Object, Function executes context sensitive VO object
Scope chain :scope chain, Scope chain , Used to correlate variable lookup to context
ES6 Start
- The basic idea is the same , Only the description of some words has changed
- The execution context station and the execution context are also the same
1. Lexical environment
Lexical environment is a canonical type , Used to define associated variables in lexical nested structures 、 Function and other identifiers
- A lexical environment consists of Environmental records (Environment Record) And a External lexical environment (oute;r Lexical Environment) form
- Environment Records( Environmental records ): This is where the variables are registered
- outer:outer It's a point , The external lexical environment containing this lexical environment , It is the key to the chain of scopes , Point to the outside Lexical Environments( Lexical environment ) References to
- A lexical context is often used to associate a Function declaration 、 Code block statements 、try-catch sentence 、evel sentence , When their code is executed , The lexical environment is created


The execution context is actually associated with two lexical environments : LexicalEnvironment and VariableEnvironment
When creating an execution context , Its LexicalEnvironment and VariableEnvironment Components initially have the same value , Their structure is exactly the same
LexicalEnvironment
LexicalEnvironment : Used for processing let、const and function Declared identifier

Once the lexical environment is created ,let、const The declared variables will also be created at the same time , But from the beginning of the scope to the area where the variable is assigned , Can't access this variable , Otherwise you will report an error , This area is also called => Temporary dead zone
VariableEnvironment
VariableEnvironment : Used for processing var Declared identifier

Once the variable environment is created , Variables will also be created at the same time , At the same time, it will be assigned undefined, Until assigned

2. Environmental records
There are two main environmental record values in this specification : Declarative environmental records and Object environment record
- Declarative environmental records : Declarative environmental records are used to define ECMAScript The effect of language grammatical elements , Such as function declaration 、 Declare variables and bind identifiers directly to ECMAScript Language values are associated Catch Clause let age = 19
- Object environment record : Object environment records are used to define ECMAScript The effect of elements , for example WithStatement, It associates the identifier binding with the properties of some objects with(obj){}


Two 、let and const
let : From an intuitive point of view ,let and var It doesn't make much difference , Are used to declare a variable
const :
- const Keywords are constant Abbreviations of words , Represents a constant 、 Measurement means
- It means that once the saved data is assigned , Can't be modified
- But if the assignment is a reference type , Then you can find the corresponding object by reference , Modify the contents of the object
1. Basic use
// let
let message = " Hello "
message2 = " The world "
console.log(message2)
// -----------------------------------------------------
// const
const str = "start"
str = "coder" // Report errors
// const Assignment reference type
const info = {
name: "star",
age: 18
}
// info = {} // Report errors
info.name = "kobe" // Modifiable 2. Temporary dead zone
Once the lexical environment is created ,let、const The declared variables will also be created at the same time , But from the beginning of the scope to the area where the variable is assigned , Can't access this variable , Otherwise you will report an error , This area is also called => Temporary dead zone
Variables are created when the lexical environment containing them is instantiated , Will be created in advance , But you can't access them , Until the lexical binding is evaluated

3. Block level scope
ES6 New block level scope... In , And through let、const、function、class The declared identifier has the limitation of block level scope
01 - Variable
console.log(message); // undefined
console.log(age); // Report errors , No definition
{
var message = 'Hello World';
let age = 18;
const height = 1.88;
}
console.log(message); // Hello World
console.log(age); // Report errors , No definition 02 - function
Different functions , There is scope promotion , But not like var That kind of promotion
foo(); // Here is the error report
{
let age = 18;
function foo() {
console.log('foo function');
}
}
// Here is accessible
foo();
// --------------------------------------
bar(); // Here is the error report
if (1) {
function bar() {
console.log('foo function');
}
}
// Here is accessible
bar();
// --------------------------------------
baz(); // Here is the error report
let str = 1;
switch (str) {
case 1:
function baz() {
console.log('foo function');
}
break;
}
// Here is accessible
baz();
3、 ... and 、let && const and var The difference between
1. Repeat statement
- let、const Duplicate statements are not allowed
- var Sure
// var Variables can be declared repeatedly
var message = "Hello World"
var message = " Hello , The world "
// let/const Repeated declaration of variables is not allowed
let address = " guangzhou "
// let address = " Shanghai " // Report errors
const info = {}
// const info = {} // Report errors 2. Scope promotion
- let、const No scope Promotion , But it will be created in the parsing phase
- var Yes
// 1.var Declared variables will be promoted in scope
console.log(message) // have access to , The value is undefined
var message = "Hello World"
// 2.let/const Declared variables : No scope Promotion
console.log(address) // Access before assignment , Report errors
let address = " guangzhou "3. Mount to window On
- let、const Will not mount
- var Meeting
// 1.var The defined variable will be added to by default window Upper
var a = "Hello World"
var b = " guangzhou "
console.log(window.a) // Hello World
console.log(window.b) // guangzhou
// 2.let/const Defined variables are not added to window Upper
let c = "Hello World"
let d = " guangzhou "
console.log(window.c) // undefined
console.log(window.d) // undefined4. Block level scope
- let、const Yes
- var No,
console.log(message); // undefined
console.log(age); // Report errors , No definition
{
var message = 'Hello World';
let age = 18;
const height = 1.88;
}
console.log(message); // Hello World
console.log(age); // Report errors , No definition var The particularity shown : For example, scope Promotion 、window Global object 、 There is no block level scope, which is a problem left over from history , It's actually JavaScript A language defect at the beginning of design
Four 、 Template string ` `
- Use `` Symbols to write strings , Call it a template string
- In template string , We can go through ${expression} To embed dynamic content
1. Basic use
const name = 'star';
const age = 18;
// 1. Data stitching
const info = `my name is ${name}, age is ${age}`;
console.log(info); // my name is star, age is 18
// 2. Simple expression operation
const bool = ` Am I an adult ?${age > 19 ? ' yes ' : ' no '}`;
console.log(bool); // Am I an adult ? no
// 3. Call function
function foo() {
return 'abc';
}
console.log(`my function is ${foo()}`); // my function is abc2. Label template string
const name = 'star';
const age = 18;
// Usage of label template string
function foo(...args) {
/**
* args
* The first parameter : By ${} Array of intercepted strings
* Later parameters : ${} Variable value passed from
*/
console.log(' Parameters :', args); // [ ['my name is ', ', age is ', ', height is ', ''] , "star", '18', '1.88' ]
}
// Use : Follow the template string after the function name
foo`my name is ${name}, age is ${age}, height is ${1.88}`;5、 ... and 、Symbol
Symbol yes ES6 A new basic data type in , Translate into symbols
- stay ES6 Before , The attribute names of objects are in string form , Then it is easy to cause the conflict of attribute names
- Symbol It can be used to generate a unique value , adopt Symbol Function , After generation, it can be used as attribute name
- Symbol Even if created many times , Value is different :Symbol After the function is executed, the value created each time is unique
1. Basic usage
// ES6 Can be used later Symbol Generate a unique value
const s1 = Symbol();
// ------ Join the object , As an object key------
// Join mode one
const obj = {
[s1]: 'aaa'
};
// Join mode 2
const s2 = Symbol();
obj[s2] = 'bbb';
// Join method 3
const s3 = Symbol();
Object.defineProperty(obj, s3, {
value: "ccc"
})2. obtain symbol Corresponding key
notes : Object.keys( ) Can't get symbol As key Of
const s1 = Symbol(); // aaa
const s2 = Symbol(); // bbb
const obj = {
name: 'why',
age: 18,
[s1]: 'aaa',
[s2]: 'bbb'
};
// You can only get ordinary ones as strings key
console.log(Object.keys(obj)); // ['name', 'age']
// Can be obtained Symbol Of key
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(), Symbol()]
const symbolKeys = Object.getOwnPropertySymbols(obj);
// 1. Through convenience , adopt Symbol Of key Get value
for (const key of symbolKeys) {
console.log(obj[key]); // aaa bbb
}
// 2. Get value directly
console.log(obj[s1]); // aaa
console.log(obj[s2]); // bbb3. description
description : You can create Symbol At the same time , Write a description
// write in description
const s3 = Symbol("ccc")
// obtain description
console.log(s3.description)
// Even if you write the same description, A new generation of Symbol It's also unique
const s4 = Symbol(s3.description)
console.log(s3 === s4) // false4. Symbol.for
If you have to generate the same Symbol : If the same key, adopt Symbol.for Can generate the same Symbol value
// This creates , Can only be
const s5 = Symbol.for("ddd")
const s6 = Symbol.for("ddd")
console.log(s5 === s6) // true
// Get incoming key
console.log(Symbol.keyFor(s5)) // ddd
6、 ... and 、Set data structure
stay ES6 Before , There are two main structures for storing data : Array 、 object
stay ES6 Two other data structures have been added to the :Set、Map, And their other forms WeakSet、WeakMap
Set Is a new data structure , Can be used to save data , It's like an array , But the difference from arrays is Elements cannot be repeated
Set A very common function is to de duplicate the array
Set Common properties : size: return Set The number of elements in ;
Set Common methods :
- add(value): Add an element , return Set Object itself ;
- delete(value): from set Delete the element equal to this value , return boolean type ;
- has(value): Judge set Is there an element in , return boolean type ;
- clear(): Empty set All the elements in , no return value ;
- forEach(callback, [, thisArg]): adopt forEach Traverse set
- Set It's supporting for of Ergodic
1. Basic use
// 1. establish Set
const set = new Set();
console.log(set);
// 2. Additive elements
set.add(10);
set.add(22);
set.add(35);
// The same elements , Add failure
set.add(22);
console.log(set); // {10, 22, 35}
// 3. Remove elements
set.delete(10);
console.log(set); // {22, 35}
// 4. Owned or not
console.log(set.has(10), set.has(35)); // false true
// 5. Traverse set
set.forEach((item) => console.log(item)); // 22 35
// 6. set Support for...of
for (const item of set) {
console.log(item); // 22 35
}2. Array weight removal
01 - loop
const names = ['abc', 'cba', 'nba', 'cba', 'nba'];
const newNames = [];
for (const item of names) {
if (!newNames.includes(item)) {
newNames.push(item);
}
}
console.log(newNames); // ['abc', 'cba', 'nba']02 - Use Set duplicate removal
const names = ['abc', 'cba', 'nba', 'cba', 'nba'];
// Turn into set, And then solve to form an array perhaps Array.from(new Set(names))
const newNames = [...new Set(names)];
console.log(newNames); // ['abc', 'cba', 'nba']7、 ... and 、weakSet data structure
Set Another similar data structure is called WeakSet , It is also a data structure whose internal elements cannot be repeated
- Difference one :WeakSet Only object types can be stored in , Cannot store basic data types
- Difference two :WeakSet The reference to the element is Weak reference , If there are no other references to an object , that GC This object can be recycled
WeakSet Common methods :
- add(value): Add an element , return WeakSet Object itself
- delete(value): from WeakSet Delete the element equal to this value , return boolean type
- has(value): Judge WeakSet Is there an element in , return boolean type
Be careful :
- because WeakSet Just a weak reference to an object , If you traverse to get the elements , Then it is possible that the object cannot be destroyed normally .
- therefore Store in WeakSet There is no way to get the object in
- That is to say , Can only be stored , You can't take it out
1. analysis

2. Application scenarios
// Weak references are used here , So when the instance object is set to empty , The data will be recycled automatically
// If strong references are used , Then the instance object is still referenced here , Then the instance object will not be recycled
const pWeakSet = new WeakSet();
class Person {
constructor() {
// Every time you create an object , Store objects in WeakSet in
pWeakSet.add(this);
}
running() {
// Determine whether the instance object that calls the method
if (!pWeakSet.has(this)) {
console.log('Type error: The way of calling is wrong ');
return;
}
console.log('running~');
}
}
let p = new Person();
p.running(); // It can be called normally running~
const runFn = p.running;
runFn(); // Report errors Type error: The way of calling is wrong
const obj = { run: runFn };
obj.run(); // Report errors Type error: The way of calling is wrong 8、 ... and 、Map data structure
The new data structure is Map, Used to store mapping relationships
- Object storage mapping can only use strings || Symbol As property name (key)
- Hope to use other types as key, Example object , At this time, the object will be automatically converted into a string as key
Map Common properties : size: return Map The number of elements in ;
Map Common methods :
- set(key, value): stay Map Add key、value, And return the whole Map object ;
- get(key): according to key obtain Map Medium value;
- has(key): Determine whether to include a key, return Boolean type ;
- delete(key): according to key Delete a key value pair , return Boolean type ;
- clear(): Empty all elements ;
- forEach(callback, [, thisArg]): adopt forEach Traverse Map
- Map It's supporting for of Ergodic
Basic use
const info = { name: 'star', age: 18 };
const obj = { id: 999 };
// 1. establish map object
const map = new Map();
// 2. Add elements
map.set(info, 'aaaa');
map.set(obj, 'bbbbb');
console.log(map); // Map(2) {
{…} => 'aaaa', {…} => 'bbbbb'}
// 3. Change content
map.set(info, 'cccc');
console.log(map); // Map(2) {
{…} => 'cccc', {…} => 'bbbbb'}
// 4. Get content
console.log(map.get(info)); // cccc
// 5. Delete content
map.delete(info);
console.log(map); // Map(1) {
{…} => 'bbbbb'}
// 6. Judge whether it exists
console.log(map.has(info), map.has(obj)); // false true
// 7. forEach Method
map.forEach((item) => console.log(item)); // bbbbb
// 8. for...of Traverse
for (const item of map) {
const [key, value] = item;
console.log(key, value); // {id: 999} 'bbbbb'
}
// 9. Empty content
map.clear();
console.log(map); // Map(0) {size: 0}Nine 、weakMap data structure
and Map Another data structure of type is called WeakMap, It also exists in the form of key value pairs
and Map The difference between :
- Difference one :WeakMap Of key Only objects can be used , Other types are not accepted as key
- Difference two :WeakMap Of key A reference to an object is a weak reference , If there are no other references to this object , that GC You can recycle the object
WeakMap There are four common methods :
- set(key, value): stay Map Add key、value, And return the whole Map object ;
- get(key): according to key obtain Map Medium value;
- has(key): Determine whether to include a key, return Boolean type ;
- delete(key): according to key Delete a key value pair , return Boolean type
Be careful :
- WeakMap It can't be traversed
- No, forEach Method , It doesn't support passing for of The way to traverse
Ten 、 Optional chain ?. Optional chain operator - JavaScript | MDN
1. Call directly : It's dangerous
const obj = {
name: "star",
friend: {
name: "coder",
running: function() {
console.log("running~")
}
}
}
// Call directly : Very dangerous
// What if there is no such method , Just report the mistake directly
obj.friend.running()2. Judgment call : so much trouble
const obj = {
name: 'star',
friend: {
name: 'coder',
running: function () {
console.log('running~');
}
}
};
// if Judge : trouble / It's not simple enough
if (obj.friend && obj.friend.running) {
obj.friend.running();
}3. call chaining : Very good
const obj = {
name: 'star',
friend: {
name: 'coder',
running: function () {
console.log('running~');
}
}
};
// 3. Usage of optional chain : ?.
/**
* obj?. => Is there a obj object
* obj?.friend?. => obj Whether there is in the object friend attribute
* obj?.friend?.running?. => obj Of friend Is there a running This method
*/
obj?.friend?.running?.();11、 ... and 、FinalizationRegistry monitor GC
FinalizationRegistry :
- FinalizationRegistry Object allows you to request a callback when an object is garbage collected
- When the registered object is recycled , It will promote the callback function
- You can call register Method , Register any object you want to clean up callbacks , Pass in the object and the values it contains
let obj = { name: 'why', age: 18 };
let info = { name: 'kobe', age: 30 };
// 2. If it's recycled , Will prompt this callback function
const finalRegistry = new FinalizationRegistry((value) => {
console.log(' An object is recycled :', value);
});
// 1. Monitor whether the registered object is recycled
finalRegistry.register(obj, 'why');
finalRegistry.register(info, 'kobe');
// 3. The assignment is null after , Will not be recycled immediately , Inert GC
// obj = null
info = null;边栏推荐
- Arm-A53资料「建议收藏」
- 多传感器融合定位(一)——3D激光里程计
- Websocket heartbeat mechanism (keep alive mechanism)
- SAP temporary tablespace error handling
- Worthington核糖核酸测定详细攻略
- Worthington丨Worthington胰蛋白酶化学性质及相关研究
- 【TA-霜狼_may-《百人计划》】美术2.2 模型基础
- 【TA-霜狼_may-《百人计划》】图形3.6 纹理压缩——包体瘦身术
- 解决:Direct local .aar file dependencies are not supported when building an AAR.
- Pycharm configuring the running environment
猜你喜欢

Urease -- Characteristics and determination scheme of Worthington jack bean urease

多传感器融合定位(三)——惯性技术

Worthington - chemical properties and related studies of Worthington trypsin

Leetcode62. 不同路径

SAP 临时表空间错误处理

Classification and determination method of Worthington stemxyme

【TA-霜狼_may-《百人计划》】美术2.2 模型基础

解决:Direct local .aar file dependencies are not supported when building an AAR.

PowerCL 批量创建及管理虚拟交换机

Solve thread safety problems & singleton mode
随机推荐
Equipped with a new generation of ultra safe cellular batteries, Sihao aipao is available from 139900 yuan
Worthington丨Worthington胰蛋白酶抑制剂说明书
什么是驱动程序签名,驱动程序如何获取数字签名?
Yolov5 learning notes (I) -- principle overview
电商数据模型设计
1-8 props的基础使用
Websocket heartbeat mechanism (keep alive mechanism)
pycharm新建项目
Ape anthropology topic 20
Oracle创建表空间和用户
Xss.haozi.me range details
SQL left connection, internal connection writing method "recommended collection"
你知道有哪些正规的兼职平台吗?
基于 FPGA 实现数字时钟详细原理讲解及验证结果
Hyperparametric optimization (grid search and Bayesian Optimization)
酪氨酸脱羧酶丨Worthington粪链球菌酪氨酸脱羧酶的特征
leetcode 763. Partition Labels 划分字母区间(中等)
Multi sensor fusion positioning (II) -- map based positioning
EN 1873 assembly accessories for roofing - plastic single roof lamps - CE certification
Hutool official website (is hutool easy to use)