当前位置:网站首页>Concept and function of ES6 symbol

Concept and function of ES6 symbol

2022-06-23 03:01:00 It workers

Concept

Symbol Is a data type that provides unique values .

effect

//ES5 We can declare a value more than once 
var a = 5;
var b = 5;
a ===b; //true

//ES6 The values declared in are never equal , Guarantee uniqueness 
let a = Symbol();
let b = Symbol();
a===b; //false

If we use it , How to get this value again ?

We can use another declarative approach :

let a = Symbol.for('abc');
let b = Symbol.for('abc');

a===b; //true

Symbol.for Not only does it declare a unique value , You will also check whether the global register has changed the value , If you have already registered , This value will be returned .

Use scenarios

let obj = {
[Symbol.for('abc')]:'111',
abc:'1234'
}

If not used Symbol, that key The value repeats , There's another situation , Is someone else inherits your object , It can also cause some problems .

So in this case Symbol, It's perfect , It will not cause a conflict .

How to get objects Symbol Value

notes : for..in.. I can't get it Symbol Of the declared value .

let a = Symbol('a');
let obj = {
[a]:'111',
b:'222',
c:'333'
}
for(let [key,value] of Object.entries(obj)){
   console.log('for of',key,value);
}
// Output :
//for of b 222
//for of c 333

So how do we take out Symbol The value of ?

Method 1 :Object.getOwnPropertySymbols

let a = Symbol('a');
let obj = {
[a]:'111',
b:'222',
c:'333'
}
Object.getOwnPropertySymbols(obj).forEach(item=>{
 console.log(obj[item])
})
// Output :
//111

Object.getOwnPropertySymbols The method will only put Symbol Return as an array , Not all key Come back , So is there any way to put all key Come back ?

Method 2 :Reflect.ownKeys

Reflect.ownKeys The method can turn all of key Values are returned .

let a = Symbol('a');
let obj = {
[a]:'111',
b:'222',
c:'333'
}
Reflect.ownKeys(obj).forEach(item=>{
console.log(obj[item]);
})
// Output :
//222
//333
//111
原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201251849419114.html