Home >Web Front-end >Front-end Q&A >What exactly is symbol in es6?

What exactly is symbol in es6?

WBOY
WBOYOriginal
2022-03-30 14:15:072740browse

symbol in es6 is a new primitive data type used to represent unique values. The biggest usage is to define the unique attribute name of an object; because Symbol is a primitive data type, not an object, so The new command cannot be used in the Symbol function stack.

What exactly is symbol in es6?

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

What exactly is 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

Parameter characteristics

The parameter of Symbol usually stores a string to identify different values. If the parameter of Symbol is an object, then the parameter will be called. The toString method of the object converts it into a string, and then generates a Symbol value.

var s1 = Symbol('id1');
var s2 = Symbol('id1');
console.log(s1 == s2);//false
var s3 = Symbol({});
console.log(s3);//Symbol([object Object])

The parameters in Symbol represent the description of the current Symbol value. Even if the parameters are the same, the two Symbol values ​​will not be the same.

Usage and features

Symbol cannot be used as an object attribute 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

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

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

Statement:
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