What is the role of Syboml data type?

We all know that learned JavaScript in JavaScript there are six kinds of basic data types: Number, String, Boolean, Null, and Undefined. The Syboml type is added in ES6 and BigInt type is added in ES10. So why the Symbl data type? Its main purpose is to solve the problem of global variable conflict. For example, we define a global object to cache data. Now we have two JS files that need to add key names to this object. Since js files are in different modules, we may add the same key names, so there will be a conflict problem. So the main function of the Symbol data type is to add unique attribute names to objects.

const obj = {}; Obj [Symbol()] = 'orange '; Obj [Symbol()] = 'pomelo' console.log(obj)Copy the code

2. Expansion of Symbol data type

The value we create through Symbol must be a unique value.

  • If we want to reuse the same Symbol value, we can use the symbol.for () method,This method takes a string as an argument. The same string must return the same Symbol value.If the parameter passed is not a string, the method automatically converts the parameter to a string.
  • There are also a number of built-in Symbol constants in the Symbol type used to identify built-in methods.
let obj1 = {}
console.log(obj1.toString())
Copy the code

If we want to modify the toString tag of the string, we can customize the string tag usingSymbol. ToStringTag this property

let obj1 ={[Symbol.toStringTag]:'Xobject'}
console.log(obj.toString())
Copy the code

We find that the string tag has been successfully modified.

  • We use the Symbol value for the property name of the object, which passes the traditionalfor... in...It’s not reachable. PassObject.keysAttribute name of type Symbol not available, use SymbolJSON.stringifySerialized objects, Symbol attribute names are also ignored.So properties of type Symbol are particularly suitable as private properties of objects!

Can’t get the Symbol attribute name? Actually, and otherwise, we can use the Object. The getOwnPropertySymbols () method, this method can only access to the Symbol type of attribute names.