-
Notifications
You must be signed in to change notification settings - Fork 9
Symbols
davidbarna edited this page Apr 8, 2018
·
1 revision
A symbol is a unique and immutable data type (added in ES6).
The
Symbolobject is an implicit object wrapper for the symbol primitive data type.
Symbol([description])A symbol is not an object, but a primitive type.
var sym1 = Symbol()
var sym2 = Symbol('foo')
console.log(sym1) // Symbol()
console.log(sym2) // Symbol(foo)
console.log(typeof sym1) // "symbol"Symbol("foo") does not coerce the string "foo" into a symbol.
It creates a new symbol each time
Symbols are always unique.
var sym1 = Symbol('foo')
var sym2 = Symbol('foo')
var obj = { [sym1]: 1, [sym2]: 2 }
sym1 == sym2 // false
sym1 === sym2 // false
obj[sym1] // 1
obj[sym2] // 2Symbol is a function.
typeof Symbol // "function"As a function, Symbol is an object with properties.
Many of them are simply global constants.
Symbol = {
/* ... */
hasInstance: Symbol(Symbol.hasInstance)
iterator: Symbol(Symbol.iterator)
search: Symbol(Symbol.search)
toPrimitive: Symbol(Symbol.toPrimitive)
toStringTag: Symbol(Symbol.toStringTag)
}...that we may talk about later on...
Symbol is not a constructor.
new Symbol('foo')
// Uncaught TypeError: Symbol is not a constructor