es6 Symbol data type

Reprinted from https://www.runoob.com/w3cnote/es6-symbol.html

Overview

ES6 introduces a new primitive data type Symbol, which represents a unique value. The biggest usage is to define the unique attribute name of an object.

In addition to Number, String, Boolean, Object, null, and undefined, ES6 data types have also added Symbol.

Basic usage

The symbol function stack cannot use the new command, because Symbol is a primitive data type, not an object. It can accept a string as a parameter and provide a description for the newly created Symbol, which is used to display it on the console or as a string for easy distinction.

let sy = Symbol("KK");
console.log(sy);   // Symbol(KK)
typeof(sy);        // "symbol"
 
// 相同参数 Symbol() 返回的值不相等
let sy1 = Symbol("kk"); 
sy === sy1;       // false

scenes to be used

As attribute name
usage

Since the value of each Symbol is not equal, the Symbol as the attribute name of the object can ensure that the attribute does not have the same name.

let sy = Symbol("key1");
 
// 写法1
let syObject = {
    
    };
syObject[sy] = "kk";
console.log(syObject);    // {Symbol(key1): "kk"}
 
// 写法2
let syObject = {
    
    
  [sy]: "kk"
};
console.log(syObject);    // {Symbol(key1): "kk"}
 
// 写法3
let syObject = {
    
    };
Object.defineProperty(syObject, sy, {
    
    value: "kk"});
console.log(syObject);   // {Symbol(key1): "kk"}

When Symbol is used as an object property name, the. Operator cannot be used, square brackets should be used. Because the. Operator is followed by a string, the string sy attribute is obtained instead of the Symbol value sy attribute.

let syObject = {
    
    };
syObject[sy] = "kk";
 
syObject[sy];  // "kk"
syObject.sy;   // undefined
important point

When the Symbol value is used as the property name, the property is a public property, not a private property, and can be accessed outside the class. But it will not appear in the loop of for...in and for...of, nor will it be returned by Object.keys() and Object.getOwnPropertyNames(). If you want to read the Symbol property of an object, you can get it through Object.getOwnPropertySymbols() and Reflect.ownKeys().

let syObject = {
    
    };
syObject[sy] = "kk";
console.log(syObject);
 
for (let i in syObject) {
    
    
  console.log(i);
}    // 无输出
 
Object.keys(syObject);                     // []
Object.getOwnPropertySymbols(syObject);    // [Symbol(key1)]
Reflect.ownKeys(syObject);                 // [Symbol(key1)]
Define constant

Use strings to represent constants in ES5. E.g:

const COLOR_RED = "red";
const COLOR_YELLOW = "yellow";
const COLOR_BLUE = "blue";

However, using a string does not guarantee that the constant is unique, which will 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 引发异常
   var colorName = getConstantName(color);
} catch (e) {
    
    
   var colorName = "unknown";
   console.log(e.message, e.name); // 传递异常对象到错误处理
}

But use Symbol to define constants, so that you can ensure that the values ​​of this group of constants are not equal. Use Symbol to modify the above example.

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 引发异常
   var colorName = getConstantName(color);
} catch (e) {
    
    
   var colorName = "unknown";
   console.log(e.message, e.name); // 传递异常对象到错误处理
}

The value of Symbol is unique, so there will be no constants with the same value, which guarantees that the switch will be executed in the way expected by the code.

Symbol.for()

Symbol.for() is similar to the singleton mode. First, it searches globally for the symbol value with the string parameter as the name in the registered Symbol. If there is, it will return the symbol value, if not, create a new one with the character The string parameter is the Symbol value of the name, and is registered in the global environment for searching.

let yellow = Symbol("Yellow");
let yellow1 = Symbol.for("Yellow");
yellow === yellow1;      // false
 
let yellow2 = Symbol.for("Yellow");
yellow1 === yellow2;     // true
Symbol.keyFor()

Symbol.keyFor() returns the key of a registered Symbol type value, which is used to check whether the symbol value of the string parameter as the name has been registered.

let yellow1 = Symbol.for("Yellow");
Symbol.keyFor(yellow1);    // "Yellow"

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/114376370