Analysis on the usage of the new feature of ES6 to the Symbol type, es6symbol
The example in this article describes the usage of the Symbol type in the new features of ES6. We will share this with you for your reference. The details are as follows:
Symbol type
1. To avoid attribute name conflicts, ES6 adds the Symbol type. A unique value can be generated for the Symbol.
let s1 = Symbol('a');let s2 = Symbol('a');console.log(s1); //Symbol(a)console.log(typeof s1); //symbolconsole.log(s1 == s2); //false
2. Symbol is used for the attribute name.
Var s1 = Symbol (); var s2 = Symbol (); var s3 = Symbol (); var obj = {[s1]: 'Hi '}; obj [s2] = 'es6'; Object. defineProperty (obj, s3, {value: 'es2015 '}); console. log (obj); // Object {Symbol (): "hi", Symbol (): "ES6", Symbol (): "ES2015"} console. log (obj. s1); // undefined-> so it cannot be used when Symbol is used as the attribute name. operator to access the property console. log (obj [s1]); // hiconsole. log (obj ['s1']); // undefined
Note:Symbol is used as the attribute name, which does not appear in... in... and... of... in the loop, it will not be Object. keys (), Object. getOwnPropertyNames () returns. Object. getOwnProertySymbols () returns an array of all the values of the current Object used as the attribute names.
2. symbol. for () accepts a string as a parameter, and then searches for the value of the Symbol with this parameter as the name. If yes, the value of this Symbol is returned, otherwise, a new Symbol value with the string name is created and returned.
3. the Symbol. keyFor () method returns a key of the registered Symbol type value.
The Symbol () method is not registered when a Symbol type is generated. Therefore, every time you call the Symbol (even if the same string is passed in), different symbrs are returned,. for () is registered when the Symbol is generated. Every time you call it again, you will first find whether there is a Symbol with the same parameters passed in. for () can be generated by Symbol. keyFor.
let s1 = Symbol('a');let s2 = Symbol('a');let s3 = Symbol.for('b');let s4 = Symbol.for('b');let name1 = Symbol.keyFor(s1);let name3 = Symbol.keyFor(s3);console.log(s1 == s2); //falseconsole.log(s1 == s3); //falseconsole.log(s2 == s3); //falseconsole.log(s3 == s4); //trueconsole.log(name1); //undefinedconsole.log(name3); //b
I hope this article will help you design the ECMAscript program.