Overview
ES6 introduces a new primitive data type, Symbol, which represents unique values. Its most important use case is to define unique property names for objects.
In addition to Number, String, Boolean, Object, null, and undefined, ES6 data types also include Symbol.
Basic Usage
The Symbol function cannot be used with the new command, because Symbol is a primitive data type, not an object. It can accept a string as a parameter to provide a description for the newly created Symbol, which is used for display in the console or when used as a string, to make it easier to distinguish.
Usage Scenarios
As Property Names
Usage
Since every Symbol value is unique, using Symbol as an object's property name can ensure that property names do not conflict.
When Symbol is used as an object property name, the dot operator cannot be used; square brackets must be used. Because what follows the dot operator is a string, what is accessed is the string sy property, not the Symbol-value sy property.
Points to Note
When a Symbol value is used as a property name, that property is public, not private, and can be accessed outside the class. However, it will not appear in for...in or for...of loops, and will not be returned by Object.keys() or Object.getOwnPropertyNames(). To read an object's Symbol properties, you can get them through Object.getOwnPropertySymbols() and Reflect.ownKeys().
Defining Constants
In ES5, strings are used to represent constants. For example:
const COLOR_RED = "red"; const COLOR_YELLOW = "yellow"; const COLOR_BLUE = "blue";
But using strings cannot guarantee that constants are unique, which can cause some problems:
But using Symbol to define constants can ensure that the values of this group of constants are all different. Use Symbol to modify the above example.
Symbol values are unique, so there will be no constants with the same value, which ensures the switch statement executes as the code intends.
Symbol.for()
Symbol.for() is similar to the singleton pattern. First, it searches globally among registered Symbols to see if there is a Symbol value with that string parameter as its name. If yes, it returns that Symbol value; if not, it creates a new Symbol value with the string parameter as its name, registers it in the global environment for future searches.
Symbol.keyFor()
Symbol.keyFor() returns the key of a registered Symbol value, which is used to check whether a Symbol value with that string parameter as its name has been registered.