Three minutes to get to know es6 Symbols

A description

Symbols JavaScript is a basic data type in the new version introduced es6, wherein each Symbol () returned from Symbol values ​​are unique.

Second, the basic usage

  • Object is added to the user a unique key
const id = Symbol('id')
let user = {
  value: '999',
  id: '001',
  [id]: 1001
}

console.log(user) // {value: "999", id: 1, Symbol(id): 1001}
console.log(user[id]) // 1001

Value of symbol can not be repeated, but may be modified

// 接上之前的代码
user[id] = 2002

console.log(user[id]) // 2002

Three, Symbol Registry

  • The Symbol () returns at each use unique symbol values ​​are
  • symbol Symbol.for () method created a global symbol will be placed in the registry
  • Symbol.keyFor () needs to pass a Symbol object, the object's return to the global register value of Symbol
Symbol.for("bar") === Symbol.for("bar"); // true
Symbol("bar") === Symbol("bar"); // false

const sym = Symbol.for("mario")
Symbol.keyFor(sym) // mario

const id = Symbol('id')
Symbol.keyFor(id) // undefined

END

Published 147 original articles · won praise 58 · views 340 000 +

Guess you like

Origin blog.csdn.net/momDIY/article/details/105346523