Home Common Problem Detailed explanation of the usage of symbol

Detailed explanation of the usage of symbol

Jul 08, 2020 pm 12:02 PM

Symbol is a new primitive data type, which is the seventh data type of JavaScript. Symbol values ​​are generated through the Symbol function, using the syntax "let s = Symbol();typeof s;", where typeof indicates that s is a symbol data type.

Detailed explanation of the usage of symbol

How to use Symbol()

Introduction: ES5 object attribute names are all strings, so It is easy to cause attribute name conflicts. For example, if a project is very large and is not developed by one person, it may cause variable name conflicts. It would be great if there is a unique name, so that attribute name conflicts can be fundamentally prevented. . This is why ES6 introduced Symbol.

ES6 introduces a new primitive data type, Symbol, which represents uniqueness. It is the seventh data type of JavaScript. Symbol values ​​are generated through the Symbol function. As long as the attribute name belongs to the Symbol type, it is unique and can be guaranteed not to conflict with other attribute names.

let s = Symbol();
typeof s;
//"symbol"
Copy after login

In the above code, s is a unique value, and typeof indicates that s is of symbol data type.

Note: The new keyword cannot be used before the symbol function, otherwise an error will be reported. This is because symbol is a primitive data type, not an object, so attributes cannot be added.

symbol can accept a string as a parameter, which represents the description of the Symbol, mainly to make it easy to distinguish when displayed on the console.

var s1 = Symbol("foo");
var s2 = Symbol("bar");
s1 // Symbol("foo")
s2 // Symbol("bar")
s1.toString() // "Symbol(foo)"
s2.toString() // "Symbol(bar)
Copy after login

This parameter can be omitted. If it is not added, it will be output on the console. It's just that the two Symbol() are not conducive to distinction, and the parameters are added to distinguish them.

Two Symbols without parameters are not equal. For example,

// 没有参数的情况
var s1 = Symbol();
var s2 = Symbol();
s1 == s2 // false
// 有参数的情况
var s1 = Symbol("foo");
var s2 = Symbol("foo");
s1 == s2 // false
Copy after login

They are not equal regardless of whether there are parameters.

Symbol cannot be operated with other values, otherwise it will Error

var s1 = Symbol("My Symbol");
"your symbol is" + s1;
// TypeError: can't convert symbol to string
`your symbol is ${s1}`
// TypeError: can't convert symbol to string
Copy after login

Symbole can be converted to a string or a Boolean value for display, but cannot be converted to a number

// 转为字符串
var s1 = Symbol("My Symbol");
String(s1) // "Symbol(My Symbol)"
s1.toString() // "Symbol(My Symbol)"
//转为布尔值
var s1 = Symbol();
Boolean(s1) //true
!s1 //false
if(s1) {
 //  ...  
}
//转为数值就会报错
Copy after login

Since each Symbol is different, it can be used as an identifier and as an attribute name of an object. , to ensure that attributes with the same name will not appear

var mySymbol = Symbol();
//第一种写法
var a = {};
a[mySymbol] = "Hello!";
//第二种写法
var a = {
     [mySymbol]: "Hellow!"
}
//第三种写法
var a = {};
Object.defineProperty(a, mySymbol, { value: "Hellow!" });
//以上写法的结果都相同
a[mySymbol] // "Hellow!"
Copy after login

Note: Symbol values ​​cannot use the dot operator when used as the attribute name of an object. Similarly, when using Symbol values ​​inside an object, they must also be placed in square brackets.

let s = Symbol();
let obj = {
    [s]: function(arg) {...}  
}
//如果s不放在[]中,该属性名就是字符串,而不是Symbol
//可以采用增强的方式在书写上面的代码
let s = Symbol();
let obj = {
    [s](arg) {...}
}
Copy after login

Symbol can also define a group of constants to ensure that the values ​​​​of this group of constants are not equal

const COLOR_RED = Symbol();
const COLOR_GREEN = Symbol();
function getComponent(color) {
    switch(color) {
        case: COLOR_RED:
               return "red";
        case: COLOR_GREEN:
              return "green";
        default:
              throw new Error("Undefind color")
    }  
}
Copy after login

The biggest advantage of using Symbol values ​​​​for constants is that any other value cannot match them. same.

Eliminate magic string

Magic string refers to a specific string or number that appears multiple times in the code and forms a strong coupling with the code. A good coding style should Eliminate magic strings and replace them with variables with clear meanings.

function getArea(shape, options) {
     var area = 0;
     switch(shape) {
          case: "Tringel":     // 魔术字符串
              area = 5*options.width*options.height;
              break;
     }
     return area;
}
getArea("Tringel", {width: 100, height: 100});    // 魔术字符串
Copy after login

Tringel in the above string is a magic string. It appears multiple times and forms a strong coupling with the code, which is not conducive to future maintenance.

var shapeType = {
   triangle: "Tringel"
}
function getArea(shape, options) {
     var area = 0;
     switch(shape) {
          case: shapeType.triangle:     // 消除魔术字符串
              area = 5*options.width*options.height;
              break;
     }
     return area;
}
getArea(shapeType.triangle, {width: 100, height: 100});    //消除魔术字符串
Copy after login

It is very suitable to use Symbol instead

var shapeType = {
   triangle: Symbol()
}
Copy after login

For more related knowledge, please visit PHP Chinese website!

The above is the detailed content of Detailed explanation of the usage of symbol. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth search deepseek official website entrance In-depth search deepseek official website entrance Mar 12, 2025 pm 01:33 PM

At the beginning of 2025, domestic AI "deepseek" made a stunning debut! This free and open source AI model has a performance comparable to the official version of OpenAI's o1, and has been fully launched on the web side, APP and API, supporting multi-terminal use of iOS, Android and web versions. In-depth search of deepseek official website and usage guide: official website address: https://www.deepseek.com/Using steps for web version: Click the link above to enter deepseek official website. Click the "Start Conversation" button on the homepage. For the first use, you need to log in with your mobile phone verification code. After logging in, you can enter the dialogue interface. deepseek is powerful, can write code, read file, and create code

deepseek web version official entrance deepseek web version official entrance Mar 12, 2025 pm 01:42 PM

The domestic AI dark horse DeepSeek has risen strongly, shocking the global AI industry! This Chinese artificial intelligence company, which has only been established for a year and a half, has won wide praise from global users for its free and open source mockups, DeepSeek-V3 and DeepSeek-R1. DeepSeek-R1 is now fully launched, with performance comparable to the official version of OpenAIo1! You can experience its powerful functions on the web page, APP and API interface. Download method: Supports iOS and Android systems, users can download it through the app store; the web version has also been officially opened! DeepSeek web version official entrance: ht

How to solve the problem of busy servers for deepseek How to solve the problem of busy servers for deepseek Mar 12, 2025 pm 01:39 PM

DeepSeek: How to deal with the popular AI that is congested with servers? As a hot AI in 2025, DeepSeek is free and open source and has a performance comparable to the official version of OpenAIo1, which shows its popularity. However, high concurrency also brings the problem of server busyness. This article will analyze the reasons and provide coping strategies. DeepSeek web version entrance: https://www.deepseek.com/DeepSeek server busy reason: High concurrent access: DeepSeek's free and powerful features attract a large number of users to use at the same time, resulting in excessive server load. Cyber ​​Attack: It is reported that DeepSeek has an impact on the US financial industry.