The ES6 Symbol data type. Most people know the concept, but don’t know where to use it.

Today we will talk about how Symbol can be played in the actual development.

Eliminate magic string

The general elimination magic string is written as:

const formAKey = 'a-form-key';
const formBKey = 'b-form-key';
const forms = {
    formAKey: {      
        getValue: () => {
            return 'I am form A';
        }
    },
    formBKey: {      
        getValue: () => {
            return 'I am form B';          
        }
    }
}

forms.formAKey.getValue() // I am form A
forms.formBKey.getValue() // I am form B
Copy the code

If Forms is global, then you need to consider property overrides if they are repeated.

Since we do not need to care about the name of the Form key created each time, it does not conflict, with Symbol we can write like this:

const formAKey = Symbol();
const formBKey = Symbol();
const forms = {
    [formAKey]: {        
        getValue: () => {
            return 'I am form A';
        }
    },
    [formBKey]: {
        getValue: () => {
            return 'I am form B';          
        }
    }
}

forms[formAKey].getValue() // I am form A
forms[formBKey].getValue() // I am form B
Copy the code

Class private attributes

Because Symbol is special and cannot be iterated by conventional methods as an attribute value, we can use it as a private attribute for internal use only

const sex = Symbol();
class Human {
    constructor(){
        this.age = 18;
        this[sex] = 'female';
    }
    getSex(){
        return this[sex];
    }
}
const human = new Human();

human.sex // undefined
human.getSex() // female
Object.keys(human) // ['age']
Copy the code

There is one drawback, however, and it is available in another new ES6 feature: Reflect

Reflect.ownKeys(human) // [ 'age', Symbol() ]
human[Reflect.ownKeys(human)[1]] // female
Copy the code

Sharing system

Symbol can also do global sharing, which is symbol.for (), which takes a string as an argument and searches for a Symbol value named for that argument. If so, the Symbol value is returned, otherwise a new Symbol value named with the string is created and registered in the global environment for searching.

const zhangsan = Symbol.for('China');
const chinese = { 
    [zhangsan]: 'I come from China'
 };
const lisi = Symbol.for('China');

chinese[zhangsan] // I come from China
chinese[lisi] // I come from China
Copy the code