In es6, Symbol can be used as an attribute name, defined variable or constant to represent a unique value. It is a new data type in es6. Two variables declared through Symbol can never be equal. The syntax is: "const name=Symbol("value")".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
What is Symbol?
Symbol is a newly added data type in es6, which represents uniqueness value. In es5, we divide data types into basic data types (string, number, Boolean, undefined, null) and reference data types (Object). The new Symbol data type in es6 is divided into basic data types
Why is there such a data type?
1 2 3 4 5 6 7 8 9 10 |
|
Since the properties and methods of objects are composed of strings, there may be conflicts when adding new methods and properties. In es6, a new data type is added to represent unique values
A unique value can be created through the Symbol function. Every time the Symbol function is executed, an object is returned.
1 2 3 4 5 |
|
In the above code, the printed values are all Symbol(). How can we distinguish who is the one? It's s1, who is s2? We can solve this problem by passing parameters
1 2 3 4 |
|
Symbol is usually used to set the property name or method of the object to prevent new The added attributes or methods conflict with the original attributes or methods
1 2 3 4 5 6 7 8 9 10 11 12 |
|
It should be noted here that the value of name must be a variable that can be changed in [].
Note 1: The parameters in Symbol are only descriptions of Symbol and have no other meaning. Therefore, even if the descriptions are the same, Symbols are different.
It can be guessed that the return value of the Symbol function is an object.
1 |
|
Note 2: The Symbol function cannot be called using the New keyword
1 |
|
Note 3: The Symbol type cannot be converted into a number during type conversion
1 2 3 4 |
|
Note 4: Symbol cannot perform any operations (maybe the return value cannot be operated)
1 2 |
|
Note 5: When Symbol is used as an object property or method, there is no way to get the value if it is not assigned to a variable
1 2 3 4 5 6 |
|
Note 6: Symbol cannot be traversed by for in loop
1 2 3 4 5 6 7 8 9 10 11 |
|
You can use Object.getOwnPropertySymbols to view all symbol properties on the object
1 |
|
[Related recommendations: javascript video tutorial 、web front end】
The above is the detailed content of What is the usage of symbol in es6. For more information, please follow other related articles on the PHP Chinese website!