


Detailed explanation of JavaScript's Symbol type, hidden attributes and global registry
This article brings you relevant knowledge about javascript, which mainly introduces issues related to Symbol types, hidden attributes and global registry, including the description of Symbol types, Symbol There will be problems such as implicit string conversion. Let's take a look at it. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
Symbol introduction
# The##Symbol type is a special type in
JavaScript. Specially, all
Symbol type values are different from each other. We can use "Symbol" to represent a unique value. The following is an example of creating a
Symbol object:
let id = Symbol();
Symbol type value, And store this value in the variable
id.
Symbol type description
When we create aSymbol type variable, we can pass in some strings with seconds attributes in the parameters. , used to describe the usage information of this variable.
For example:
let id1 = Symbol('狂拽酷炫吊炸天的小明的id'); let id2 = Symbol('低调奢华有内涵的婷婷的id');
Symbol Types are different at any time, even if they have the same description information, the description is just a label and has no other purpose For example:
let id1 = Symbol('id'); let id2 = Symbol('id'); console.log(id1==id2);//false
Symbol cannot intuitively see the internal specific value. By adding a description information, let us define the variable Have a more intuitive understanding of its uses.
Symbol does not convert to string implicitly
Most types in JavaScript can be directly converted to string type output, so we We cannot intuitively see what its value is. For example, we can directly use
alert(123) to convert the number
123 into a string and pop it up.
However, the
Symbol type is special and cannot be converted directly. For example: the
Symbol
let id = Symbol(); alert(id);//报错,不能把Symbol类型转为字符串
JavaScript cannot be converted into characters. Strings are due to their inherent "language protection" mechanism to prevent language confusion. Because strings and
Symbol are essentially different, one should not be converted into the other.
Just imagine, if Symbol can be converted to a string, then it becomes a function that generates a unique string, and there is no need for an independent data type.
Symbol variable, we can use the
.toString() method as follows:
let id = Symbol('this is identification'); console.log(id.toString());//Symbol(this is identification);
.description attribute to obtain description information:
let id = Symbol('加油,奥利给'); console.log(id.description);//加油,奥利给”
JavaScript, there are only two types The value can be used as the attribute key of the object:
- String
- Symbol
Create Symbol key
There are two ways to useSymbol as a key value:
Example 1:
let id = Symbol('id'); let user = {}; user[id] = 'id value';//添加Symbol键 console.log(user[id]);//id value
let id = Symbol('id'); let user = { [id]:'id value',//注意这里的方括号 }; console.log(user[id]);
Symbol type as a key into an object. It should be noted that you need to use
obj[id when accessing properties. ] instead of
obj.id, because
obj.id represents
obj['id'].
Symbol as the key of the object?
for...in is skipped
SymbolA very obvious feature is that if
Symbol is used in the object As a key, properties of type
Symbol cannot be accessed using the
for...in statement.
let id = Symbol('id'); let user = { name : 'xiaoming', [id] : 'id', }; for (let key in user) console.log(user[key]);
> xiaoming
[id] object is not printed comes out, indicating that in the object attribute list, using
for ... in will automatically ignore keys of type
Symbol.
Object.keys(user) will also ignore all
Symbol type keys.
Symbol key, the
Object.assign method can copy all attributes:
let id = Symbol(); let obj = { [id] : '123' } let obj2 = Object.assign({},obj); console.log(obj2[id]);
Symbol, because the copied object still cannot obtain the
Symbol key.
隐藏自定义属性
由于Symbol
既不能直接转为字符串,我们没有办法直观的获得它的值,又不能通过for … in
获得对象的Symbol
属性,也就是说,如果没有Symbol
变量本身,我们就没有办法获得对象内部的对应属性。
因此,通过Symbol
类型的键值,我们可以隐藏属性,这些属性只能我们自己访问,其他人都看不到我们的属性。
举个例子:
我们在开发的过程中,需要和同事“张三”合作,而这个张三创建了一个非常好用的工具Tool
,Tool
是一个对象类型,我们想白嫖张三的Tool
,并在此基础上添加一些自己的属性。
我们就可以通过添加Symbol
类型的键:
let tool = {//张三写好了的Tool usage : "Can do anything", } let name = Symbol("My tool obj"); tool[name] = "This is my tool"; console.log(tool[name]);
以上示例展示了如何在别人写好的对象上添加自己的属性,那么为什么要使用Symbol
类型而不是常规的字符串呢?
原因如下:
- 对象
tool
是别人写好的代码,原则上我们不应该去修改别人的代码,这样会造成风险; - 避免命名冲突,我们直接使用字符串很有可能会和别人原有的属性键冲突,造成严重的后果;
- 使用
Symbol
永远不会发生命名冲突,因为Symbol
都是不同的; - 别人无法访问
Symbol
类型的键,相当于不会和别人的代码冲突;
错误示范:
如果我们不使用Symbol
类型,很可能出现以下情况:
let tool = {//张三写好了的Tool usage : "Can do anything", } tool.usage = "Boom Boom"; console.log(tool.usage);
以上代码由于重复使用”usage”,从而重写了原属性,会造成对象原功能异常。
Symbol全局注册表
所有的Symbol
变量都是不同的,即使他们有用相同的标签(描述)。
有些时候,我们希望通过一个字符串名称(标签),访问同一个Symbol
对象,例如我们在代码的不同地方访问相同的Symbol
。
JavaScript
会维护一个全局的Symbol
注册表,我们可以通过向注册表中插入Symbol
对象,并为对象起一个字符串名称访问该对象。
向注册表插入或者读取Symbol
对象需要使用Symbol.for(key)
方法,如果注册表中有名为key
的对象,就返回该对象,否则就插入新对象再返回。
举个例子:
let id1 = Symbol.for('id');//注册表内没有名为id的Symbol,创建并返回 let id2 = Symbol.for('id');//注册表内已有名为id的Symbol,直接返回 console.log(id1===id2);//true
我们通过Symbol.for(key)
就能以全局变量的方式使用Symbol
对象,并使用一个字符串标记对象的名字。
相反的,我们还可以使用Symbol.keyFor(Symbol)
反向的从对象获取名称。
举个例子:
let id = Symbol.for('id');//注册表内没有名为id的Symbol,创建并返回 let name = Symbol.keyFor(id); console.log(name);//id
Symbol.keyFor()
函数只能用在全局Symbol
对象上(使用Symbol.for
插入的对象),如果用在非全局对象上,就会返回undefined
。
举个例子:
let id = Symbol('id');//局部Symbol let name = Symbol.keyFor(id); console.log(name);//undefined
系统Symbol
JavaScript
有许多系统Symbol
,例如:
Symbol.hasInstance
Symbol.iterator
Symbol.toPrimitive
它们各有用途,我们在后面的会逐步介绍道这些独特的变量。
总结
-
Symbol
对象的值是唯一的; -
Symbol
可以添加一个标签,并通过标签在全局注册表中查询对象的实体; -
Symbol
作为对象的键无法被for … in
探测到; - 我们可以通过
Symbol
到全局注册表访问全局的Symbol
对象;
但是,Symbol
并不是完全隐藏的,我们可以通过Object.getOwnPropertySymbols(obj)
获取对象所有的Symbol
,或者通过Reflect.ownKeys(obj)
获取对象所有的键。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Detailed explanation of JavaScript's Symbol type, hidden attributes and global registry. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
