Home > Common Problem > Detailed explanation of the usage of symbol

Detailed explanation of the usage of symbol

藏色散人
Release: 2020-07-08 12:02:37
Original
14131 people have browsed it

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!

Related labels:
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