M: What do you mean by Symbol

You can pay attention to my public number “life code”, a dry goods every day

Basic data types

When an interviewer asks you what the basic types of JS are, you might say:

  • Number,
  • String,
  • Boolean,
  • Undefined,
  • Null.

In ES6, there is a new one called:

  • Symbol

What does that mean? Represents a unique, unique value. The largest use is to define the name of a unique property of an object.

Symbol’s problem

Special attention should be paid to:

  • The Symbol stack cannot use the new command because it is a primitive type and cannot use the new operation
var s = new Symbol(a)/ / an error

VM161:1 Uncaught TypeErrorSymbol is not a constructor

    at new Symbol (<anonymous>)

    at <anonymous>:1:9

Copy the code
  • Cannot use JSON. Parse JSON. Stringify deep copy
var Ken = Symbol('kk')

var obj = {name: Ken}

var copy = JSON.parse(JSON.stringify(obj))

console.log(copy)// You will notice that the name attribute is missing

Copy the code
  • The only property
let Ken = Symbol("KK");

console.log(Ken);   // Symbol(KK)

typeof(Ken);        // "symbol"

 

// Symbol() returns unequal values for the same argument

let Ken1 = Symbol("KK"); 

Ken === Ken1;       // false

Copy the code
  • When used as an object attribute key, it can only be used when obtaining its value[]Form get, cannot be used.The operator
let Ken = {};

Ken[sy] = "kk";

 

Ken[sy];  // "kk"

Ken.sy;   // undefined

Copy the code
  • When the Symbol value is used as the attribute name, the attribute is public, not private, and can be accessed outside the class

But not in the for… In, for… Of the loop, will not be the Object. The keys (), Object. GetOwnPropertyNames () returns. If you want to read to the Symbol attribute of an Object, you can through the Object. The getOwnPropertySymbols () and Reflect ownKeys () to get.

let Ken = {};

Ken[sy] = "kk";

console.log(Ken);

 

for (let i in Ken) {

  console.log(i);

}    / / no output

 

Object.keys(Ken);                     / / []

Object.getOwnPropertySymbols(Ken);    // [Symbol(key1)]

Reflect.ownKeys(Ken);                 // [Symbol(key1)]

Copy the code
  • Define constants

In ES5, strings are used to represent constants. Such as:

const COLOR_RED = "red";

const COLOR_YELLOW = "yellow";

const COLOR_BLUE = "blue";

Copy the code

But using strings does not guarantee that constants are unique, which can cause some problems:

const COLOR_RED = "red";

const COLOR_YELLOW = "yellow";

const COLOR_BLUE = "blue";

const MY_BLUE = "blue";

 

function ColorException(message{

   this.message = message;

   this.name = "ColorException";

}

 

function getConstantName(color{

    switch (color) {

        case COLOR_RED :

            return "COLOR_RED";

        case COLOR_YELLOW :

            return "COLOR_YELLOW ";

        case COLOR_BLUE:

            return "COLOR_BLUE";

        case MY_BLUE:

            return "MY_BLUE";         

        default:

            throw new ColorException("Can't find this color");

    }

}

 

try {

   

   var color = "green"// Green throws an exception

   var colorName = getConstantName(color);

catch (e) {

   var colorName = "unknown";

   console.log(e.message, e.name); // Pass the exception object to the error handler

}

Copy the code

But using Symbol to define constants ensures that the values of the constants are not equal. Modify the above example with Symbol.

const COLOR_RED = Symbol("red");

const COLOR_YELLOW = Symbol("yellow");

const COLOR_BLUE = Symbol("blue");

 

function ColorException(message{

   this.message = message;

   this.name = "ColorException";

}

function getConstantName(color{

    switch (color) {

        case COLOR_RED :

            return "COLOR_RED";

        case COLOR_YELLOW :

            return "COLOR_YELLOW ";

        case COLOR_BLUE:

            return "COLOR_BLUE";

        default:

            throw new ColorException("Can't find this color");

    }

}

 

try {

   

   var color = "green"// Green throws an exception

   var colorName = getConstantName(color);

catch (e) {

   var colorName = "unknown";

   console.log(e.message, e.name); // Pass the exception object to the error handler

}

Copy the code