


Detailed explanation of JavaScript's Symbol type, hidden attributes and global registry
Jun 02, 2022 am 11:50 AMThis 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();In this way we create a
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('低調(diào)奢華有內(nèi)涵的婷婷的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);//falseThe meaning of this tag, I personally think it is related to the fact that
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類型轉(zhuǎn)為字符串
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);or Use the
.description attribute to obtain description information:
let?id?=?Symbol('加油,奧利給'); console.log(id.description);//加油,奧利給”Symbol is similar to the property key of an objectAccording to the specifications of
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?valueExample 2:
let?id?=?Symbol('id'); let?user?=?{ [id]:'id?value',//注意這里的方括號 }; console.log(user[id]);The above two cases show the use of inserting the
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]);Execute the above code and get the following results:
>?xiaomingIt can be found that the value of the
[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]);This does not affect Hidden properties of
Symbol, because the copied object still cannot obtain the
Symbol key.
隱藏自定義屬性
由于Symbol
既不能直接轉(zhuǎn)為字符串,我們沒有辦法直觀的獲得它的值,又不能通過for … in
獲得對象的Symbol
屬性,也就是說,如果沒有Symbol
變量本身,我們就沒有辦法獲得對象內(nèi)部的對應(yīng)屬性。
因此,通過Symbol
類型的鍵值,我們可以隱藏屬性,這些屬性只能我們自己訪問,其他人都看不到我們的屬性。
舉個例子:
我們在開發(fā)的過程中,需要和同事“張三”合作,而這個張三創(chuàng)建了一個非常好用的工具Tool
,Tool
是一個對象類型,我們想白嫖張三的Tool
,并在此基礎(chǔ)上添加一些自己的屬性。
我們就可以通過添加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
類型而不是常規(guī)的字符串呢?
原因如下:
- 對象
tool
是別人寫好的代碼,原則上我們不應(yīng)該去修改別人的代碼,這樣會造成風險; - 避免命名沖突,我們直接使用字符串很有可能會和別人原有的屬性鍵沖突,造成嚴重的后果;
- 使用
Symbol
永遠不會發(fā)生命名沖突,因為Symbol
都是不同的; - 別人無法訪問
Symbol
類型的鍵,相當于不會和別人的代碼沖突;
錯誤示范:
如果我們不使用Symbol
類型,很可能出現(xiàn)以下情況:
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');//注冊表內(nèi)沒有名為id的Symbol,創(chuàng)建并返回 let?id2?=?Symbol.for('id');//注冊表內(nèi)已有名為id的Symbol,直接返回 console.log(id1===id2);//true
我們通過Symbol.for(key)
就能以全局變量的方式使用Symbol
對象,并使用一個字符串標記對象的名字。
相反的,我們還可以使用Symbol.keyFor(Symbol)
反向的從對象獲取名稱。
舉個例子:
let?id?=?Symbol.for('id');//注冊表內(nèi)沒有名為id的Symbol,創(chuàng)建并返回 let?name?=?Symbol.keyFor(id); console.log(name);//id
Symbol.keyFor()
函數(shù)只能用在全局Symbol
對象上(使用Symbol.for
插入的對象),如果用在非全局對象上,就會返回undefined
。
舉個例子:
let?id?=?Symbol('id');//局部Symbol let?name?=?Symbol.keyFor(id); console.log(name);//undefined
系統(tǒng)Symbol
JavaScript
有許多系統(tǒng)Symbol
,例如:
Symbol.hasInstance
Symbol.iterator
Symbol.toPrimitive
它們各有用途,我們在后面的會逐步介紹道這些獨特的變量。
總結(jié)
-
Symbol
對象的值是唯一的; -
Symbol
可以添加一個標簽,并通過標簽在全局注冊表中查詢對象的實體; -
Symbol
作為對象的鍵無法被for … in
探測到; - 我們可以通過
Symbol
到全局注冊表訪問全局的Symbol
對象;
但是,Symbol
并不是完全隱藏的,我們可以通過Object.getOwnPropertySymbols(obj)
獲取對象所有的Symbol
,或者通過Reflect.ownKeys(obj)
獲取對象所有的鍵。
【相關(guān)推薦: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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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

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.

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

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

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 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).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
