What is the function of symbols in es6

WBOY
Release: 2022-04-08 10:39:42
Original
3866 people have browsed it

The role of symbol in es6: 1. Used as an attribute name. Symbol represents a unique value, which can ensure that attributes do not have duplicate names and can also be accessed outside the class; 2. Used to define constants, which are A new primitive data type with the syntax "const name=Symbol("value")".

What is the function of symbols in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

What is the role of symbol in es6

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 also add Symbol.

Basic usage

Symbol function stack cannot use the new command because Symbol is a primitive data type, not an object. You can accept a string as a parameter to provide a description for the newly created Symbol, which can be displayed on the console or used as a string for easy differentiation.

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

As an attribute name

Usage

Since the value of each Symbol is not equal, Symbol is used as The attribute name of the object can ensure that the attributes do not have duplicate names.

What is the function of symbols in es6

#Symbol cannot be used as an object property name. The . operator must be used, and square brackets must be used. Because the . operator is followed by a string, the string sy attribute is obtained, not the Symbol value sy attribute.

let syObject = {};
syObject[sy] = "kk";
 
syObject[sy];  // "kk"
syObject.sy;   // undefined
Copy after login

Notes

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 loops 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)]
Copy after login

Define constants

Use strings to represent constants in ES5. For example:

const COLOR_RED = "red";
const COLOR_YELLOW = "yellow";
const COLOR_BLUE = "blue";
Copy after login

But using strings cannot guarantee that constants are unique, which will cause some problems:

But using Symbol to define constants can ensure that the values ​​of this set of constants are unique. equal. Modify the above example using 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 引发异常
   var colorName = getConstantName(color);
} catch (e) {
   var colorName = "unknown";
   console.log(e.message, e.name); // 传递异常对象到错误处理
}
Copy after login

The value of Symbol is unique, so there will be no constants with the same value, which ensures that the switch executes as expected by the code.

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What is the function of symbols in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template