Het gegevenstype symbool is een primitief gegevenstype. De Symbol() functie geeft een waarde terug (returns a value) van het type symbool, heeft statische eigenschappen die verscheidene leden van ingebouwde objecten blootstelt, heeft statische methoden die het globale symbolregister blootstellen en vertegenwoordigd een ingebouwde objectklasse. Maar is onvolledig als een constructor, omdat het niet de "new Symbol()" syntaxis ondersteund.
Elke waarde teruggekregen van Symbol() is uniek. Zo'n teruggekregen waarde kan, bijvoorbeeld, gebruikt worden als identificatiemiddel voor objecteigenschappen; het primaire doel van dit gegevenstype. Hoewel er andere use-cases zijn, zoals het beschikbaar maken van ondoorzichtige gegevenstypen of als algemeen uniek identificatiemiddel. Meer uitleg over het doel en gebruik van het symbool is te vinden in de woordenlijst.
Beschrijving
Om een nieuw primitief symbool te creëren, schrijf je Symbol()
met een optionele String als beschrijving:
let sym1 = Symbol()
let sym2 = Symbol('foo')
let sym3 = Symbol('foo')
De bovenstaande code creëert drie nieuwe symbolen. Let er op dat Symbol("foo")
niet de string "foo"
omzet naar een symbool maar dat het telkens een nieuw uniek symbool creëert:
Symbol('foo') === Symbol('foo') // false
De volgende syntaxis met de new
operator zal een TypeError
: afwerpen:
let sym = new Symbol() // TypeError
Dit behoed auteurs ervoor om nadrukkelijk een Symbol
wrapper-object te creëren in plaats van een nieuwe symboolwaarde. Terwijl normaal gesproken primitieve gegevenstypen wel gemaakt kunnen worden met een wrapper-object. (Zoals: new Boolean
, new String
en new Number
).
Als je echt een Symbol
wrapper-object wilt maken, kun je dit doen met de Object()
functie:
let sym = Symbol('foo')
typeof sym // "symbol"
let symObj = Object(sym)
typeof symObj // "object"
Gedeelde symbolen in het globale symboolregister
De bovenstaande syntaxis, die gebruik maakt van de Symbol()
functie, creëert alleen niet een globaal symbool dat te gebruiken is door je gehele codebase. Om symbolen te creëren die door al je bestanden en zelfs door je realms (met elk hun eigen globale scope) te gebruiken zijn; gebruik je de methoden Symbol.for()
en Symbol.keyFor()
. Om, respectievelijk, symbolen in het globale symbolenregister aan te maken en terug te krijgen.
Symbooleigenschappen vinden in objecten
De methode Object.getOwnPropertySymbols()
geeft een array met symbolen terug en laat je symbooleigenschappen vinden in een opgegeven object. Let er op dat elk object geïnitialiseerd wordt zonder eigen symbooleigenschappen, dus deze array zal leeg zijn tenzij je een symbool als eigenschap hebt gegeven aan een object.
Constructor
Symbol()
- De
Symbol()
constructor geeft een waarde terug van het type symbol, maar is incompleet als een constructor omdat het niet de "new Symbol()
" syntaxis ondersteund.
Static properties
Symbol.asyncIterator
- A method that returns the default AsyncIterator for an object. Used by
for await...of
. Symbol.hasInstance
- A method determining if a constructor object recognizes an object as its instance. Used by
instanceof
. Symbol.isConcatSpreadable
- A Boolean value indicating if an object should be flattened to its array elements. Used by
Array.prototype.concat()
. Symbol.iterator
- A method returning the default iterator for an object. Used by
for...of
. Symbol.match
- A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by
String.prototype.match()
. Symbol.matchAll
- A method that returns an iterator, that yields matches of the regular expression against a string. Used by
String.prototype.matchAll()
. Symbol.replace
- A method that replaces matched substrings of a string. Used by
String.prototype.replace()
. Symbol.search
- A method that returns the index within a string that matches the regular expression. Used by
String.prototype.search()
. Symbol.split
- A method that splits a string at the indices that match a regular expression. Used by
String.prototype.split()
. Symbol.species
- A constructor function that is used to create derived objects.
Symbol.toPrimitive
- A method converting an object to a primitive value.
Symbol.toStringTag
- A string value used for the default description of an object. Used by
Object.prototype.toString()
. Symbol.unscopables
- An object value of whose own and inherited property names are excluded from the
with
environment bindings of the associated object.
Static methods
Symbol.for(key)
- Searches for existing symbols with the given
key
and returns it if found. Otherwise a new symbol gets created in the global symbol registry withkey
. Symbol.keyFor(sym)
- Retrieves a shared symbol key from the global symbol registry for the given symbol.
Instance properties
Symbol.prototype.description
- A read-only string containing the description of the symbol.
Instance methods
Symbol.prototype.toSource()
- Returns a string containing the source of the
Symbol
object. Overrides theObject.prototype.toSource()
method. Symbol.prototype.toString()
- Returns a string containing the description of the Symbol. Overrides the
Object.prototype.toString()
method. Symbol.prototype.valueOf()
- Returns the primitive value of the
Symbol
object. Overrides theObject.prototype.valueOf()
method. Symbol.prototype[@@toPrimitive]
- Returns the primitive value of the
Symbol
object.
Examples
Using the typeof operator with symbols
The typeof
operator can help you to identify symbols.
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'
Symbol type conversions
Some things to note when working with type conversion of symbols.
- When trying to convert a symbol to a number, a
TypeError
will be thrown
(e.g.+sym
orsym | 0
). - When using loose equality,
Object(sym) == sym
returnstrue
. Symbol("foo") + "bar"
throws aTypeError
(can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example.- The "safer"
String(sym)
conversion works like a call toSymbol.prototype.toString()
with symbols, but note thatnew String(sym)
will throw.
Symbols and for...in iteration
Symbols are not enumerable in for...in
iterations. In addition, Object.getOwnPropertyNames()
will not return symbol object properties, however, you can use Object.getOwnPropertySymbols()
to get these.
let obj = {}
obj[Symbol('a')] = 'a'
obj[Symbol.for('b')] = 'b'
obj['c'] = 'c'
obj.d = 'd'
for (let i in obj) {
console.log(i) // logs "c" and "d"
}
Symbols and JSON.stringify()
Symbol-keyed properties will be completely ignored when using JSON.stringify()
:
JSON.stringify({[Symbol('foo')]: 'foo'})
// '{}'
For more details, see JSON.stringify()
.
Symbol wrapper objects as property keys
When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol:
let sym = Symbol('foo')
let obj = {[sym]: 1}
obj[sym] // 1
obj[Object(sym)] // still 1
Specifications
Browser compatibility
BCD tables only load in the browser