Article From:https://www.cnblogs.com/jiqing9006/p/9306148.html

Symbol

let s1 = Symbol('foo');
let s2 = Symbol('bar');

s1 // Symbol(foo)
s2 // Symbol(bar)

s1.toString() // "Symbol(foo)"
s2.toString() // "Symbol(bar)"

ES6 A new primitive data type Symbol is introduced to represent unique values.

// No parameterLet S1 = Symbol ();Let S2 = Symbol ();S1 = = = = S2 / / false/ / with a parameterLet S3 = Symbol ('foo');Let S4 = Symbol ('foo');S3 = = = = S4 / / false

Application case

const log = {};

log.levels = {
  DEBUG: Symbol('debug'),
  INFO: Symbol('info'),
  WARN: Symbol('warn')
};
console.log(log.levels.DEBUG, 'debug message');
console.log(log.levels.INFO, 'info message');
const obj = {};
let a = Symbol('a');
let b = Symbol('b');

obj[a] = 'Hello';
obj[b] = 'World';

const objectSymbols = Object.getOwnPropertySymbols(obj);

objectSymbols
// [Symbol(a), Symbol(b)]

The traversal of the attribute name.

Sometimes, we want to use the same Symbol value again, and the Symbol.for method can do this.

let s1 = Symbol.for('foo');
let s2 = Symbol.for('foo');

s1 === s2 // true
Symbol.for("bar") === Symbol.for("bar")
// true

Symbol("bar") === Symbol("bar")
// false
Link of this Article: Symbol of the new features of ES6

Leave a Reply

Your email address will not be published. Required fields are marked *