Symbol data type
In JS, there are six data types before ES6.
ES6 introduced the symbol data type, so symbol is js’s seventh data type, representing unique values. Is a data type similar to a string.
The origin of symbol
Object attribute names in ES5 are all strings, which can easily cause attribute name conflicts. For example, if you use an object provided by someone else and want to add a new method to the object (the mixin pattern), the name of the new method may conflict with the existing method. It would be nice if there were a mechanism to ensure that each property name was unique, preventing property name conflicts at all. This is why ES6 introduced Symbol
Symbol characteristics
-
The value of Symbol is unique and is used to resolve naming conflicts
-
Slymbol values cannot be computed with other data
-
Object properties defined by Symbol cannot use fr.. In loops through, but you can use reflect.ownkeys to get all the key names of the object
-
Do not use the new command before the Symbol function, otherwise an error will be reported. This is because the generated Symbol is a primitive type value, not an object. That is, because the Symbol value is not an object, attributes cannot be added. Basically, it’s a data type similar to a string.
// create Symbol let s= Symbol(); console.log(s, typeof s); Let s2 = symbol (' rb'); Let s3 = Symbol(' rb'); console.log(s2 === s3); //false // create the same Symbol with symbol. for let s4 = symbol. for(' rb'); Let s5 = Symbol. For (' rb'); console.log(s4 === s5); Let result = s + 100; / / an error,Copy the code
The article concludes with a review of JS data types referencing a mnemonic from Silicon Valley
// u=>undefined // s=>string symbol // 0=>object // n=>null number // b=> BooleanCopy the code
Think about it, decide to write a little bit more,
The application of symbol
Add up and Down methods to the RB object
Method 1
Let rb = {name: 'Japanese war criminal ', age: 500,}; Symbol() let methods = {up: symbol(), down: symbol()}; Rb [methods.up] = function () {console.log(' forgive me for saying people '); }; Rb [methods.down] = function () {console.log(); }; console.log(rb);Copy the code
Method 2
Add sb and DSB methods to the RB object
Let rb = {name: 'Japanese war prisoner ', age: 500, [Symbol('sb')]: function () {console.log(' I like Japanese animation '); }, [Symbol(' DSB ')]: function () {console.log(' but not to prevent I do not like their crimes in China '); }}; console.log(rb);Copy the code