The ES5 object property name is a string that can easily cause a violation of property names.
Eg:var a = {name: ' lucy '};a.name = ' Lili ';
This will override the property
ES6 introduces a new primitive data type, symbol, that represents a unique value.
Re-review the new knowledge: There are 6 basic data types: Undefined, Null, Boolean (Boolean), String (string), numeric (number), objects (object).
Here's a new addition: Symbol
Note that the Symbol
command cannot be used before the function new
, otherwise it will be an error. This is because the generated symbol is a value of the original type, not an object
Symbol
A function can accept a string as a parameter, representing a description of the symbol instance, primarily for display in the console, or for a string, to be easily distinguishable.
// Conditions without parameters var s1 = Symbol (); var s2 =// false// parameter in case var s1 = Symbol ("foo") ; var s2 = Symbol ("foo"// false
Symbol values cannot be evaluated with other types of values
Symbol as the property name
varMysymbol =Symbol ();//The first form of a notationvarA ={};a[mysymbol]= ' hello! ';//The second type of notationvarA ={[Mysymbol]:' Hello! '};//The Third kind of wordingvarA ={};object.defineproperty (A, Mysymbol, {value:' Hello! ' });//The same result is found in the above notationA[mysymbol]//"Hello!"
Note that you cannot use the dot operator when the symbol value is used as the object property name.
var a = {}; var name == ' Lili '= ' Lucy '; Console.log (A.name,a[name]); // Lili,lucy
When a symbol value is a property name, the property is also exposed, not a private property.
This is somewhat similar to the protected attribute in Java (the difference between protected and private: The outside of the class is inaccessible, subclasses within a class can inherit protected can not inherit private)
But the symbol here is also accessible outside the class, but it will not appear in for...in
, for...of
loop, or be Object.keys()
Object.getOwnPropertyNames()
returned. But there is a Object.getOwnPropertySymbols
way to get all the symbol property names for the specified object
Symbol.for (), Symbol.keyfor ()
The symbol.for mechanism is somewhat analogous to a singleton pattern, first searching globally for a symbol value with that parameter as its name, and if so, returns the symbol value, or creates a new and returns a symbol value that is the name of the string. and the direct symbol is a little different.
var s1 = Symbol. for (' foo '); var s2 = Symbol. for (' foo '// true
The Symbol.keyfor method returns a key for a registered symbol type value. The essence is to detect whether the symbol has been created
var s1 = Symbol. for ("foo"// "foo"var s2 = Symbol ("foo"// undefined
Built-in symbol value
There are 11 ways to view http://es6.ruanyifeng.com/#docs/symbol
ES6 the symbol of entry