ES 6 introduces a new data type, Symbol. What is it used for?

To illustrate the use of Symbol, let’s describe a usage scenario.

We’re making a game application where the user has to choose the race of the character.

Var race = {protoss: 'protoss', // Protoss Terran: 'Terran ', // Terran zerg: 'Zerg' // Zerg} function createRole(type){if(type === race.protoss){create Protoss character} else if(type === race.terran){create Human character} else If (type === race.zerg){Create zerg characters}}Copy the code

After the user selects the race, createRole is called to create the role:

// Pass the string createRole('zerg') // or pass the variable createRole(race.zerg)Copy the code

Passing in strings is generally considered bad practice, so use createRole(race.zerg) more.

If createRole(race.zerg) is used, the smart reader will notice that it doesn’t matter what the values of Race.protoss, race.terran, race.zerg are.

CreateRole (race.zerg) has no effect if it is written as follows:

var race = { protoss: 'askdjaslkfjas; lfkjas; FLKJ ', // Protoss Terran: '; lkfalksjfl; askjfsfal; SKFJ ', / / Terran, zerg: 'qwieqwoirqwoiruoiwqoisrqwroiu' / / zerg}Copy the code

In other words:

It doesn’t matter what race.zerg value is, as long as its value is different from race.protoss and Race.Terran.

That’s what Symbol does: It creates a unique value (but not a string).

Rewrite the above race with Symbol:

var race = { protoss: Symbol(), terran: Symbol(), zerg: Symbol() } race.protoss ! == race.terran // true race.protoss ! == race.zerg // trueCopy the code

You can also give each Symbol a name:

var race = {
  protoss: Symbol('protoss'),
  terran: Symbol('terran'),
  zerg: Symbol('zerg')
}
Copy the code

This name is not related to the value of the Symbol. The following code proves that the name of Symbol is independent of the value:

var a1 = Symbol('a') var a2 = Symbol('a') a1 ! == a2 // trueCopy the code

If you think my words are still too complicated to understand, you can remember a sentence:

The Symbol value generates a globally unique value using the Symbol function.

Above, is a brief description of Symbol, more detailed and authoritative knowledge refer to the self-study link below.

Self-study links:

MDN: symbol-javascript

Ruan Yifeng: Getting started with ECMAScript 6