Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Symbol types, Hidden attributes and Global Registry instance Analysis of JavaScript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this "JavaScript Symbol type, hidden attributes, global registry instance analysis" article, so the editor summarizes the following contents to you, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "JavaScript Symbol type, hidden attributes, global registry instance analysis" article.

Use of the Symbol type

The following is a brief introduction to its usage and usage scenarios.

Introduction to Symbol

Symbol type is a special type of JavaScript, especially in that all Symbol type values are different from each other. We can use "Symbol" to represent a unique value. Here is an example of creating a Symbol object:

Let id = Symbol ()

So we create a value of type Symbol and store that value in the variable id.

Description of the Symbol type

When we create a variable of type Symbol, we can pass a string of seconds attribute in the parameter to describe the purpose of the variable.

For example:

Let id1 = Symbol ('id' of Xiao Ming who blows up the sky); let id2 = Symbol (' low-key, luxurious and connotative id' of Tingting)

Symbol types are different at any time, even if they have the same description information and the description is just a tag, there is no other use, such as:

Let id1= Symbol ('id'); let id2 = Symbol (' id'); console.log (id1==id2); / / false

The meaning of this tag has something to do with the fact that Symbol can not directly see the internal specific values. By adding a description, we can have a more intuitive understanding of the use of variables.

Symbol does not implicitly convert strings

Most types in JavaScript can be directly converted to string type output, so we can't directly see what its value is. For example, we can directly convert the number 123 to string pop-up with alert (123).

But the Symbol type is special and cannot be converted directly, for example:

Let id = Symbol (); alert (id); / / error, cannot convert Symbol type to string

The Symbol type in JavaScript cannot be converted to a string because of its inherent "language protection" mechanism against language confusion, because strings are fundamentally different from Symbol and should not be converted into the other.

Imagine that if Symbol could be converted to a string, it would become a function that generates a unique string, eliminating the need for independent data types.

If we really want to know the value of the 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 get the description information:

Let id = Symbol ('come on, Ollie gives'); console.log (id.description); / / come on, Ollie gives "Symbol similar to the property key as an object"

According to the JavaScript specification, there are only two types of values that can be used as property keys for objects:

String

Symbol

If you use another type, it is implicitly converted to a string type. The keys of the object are described in detail in the previous section and will not be repeated here.

Create Symbol key

There are two ways to use Symbol as a key value:

Example 1:

Let id = Symbol ('id'); let user = {}; user [id] =' id value';// add symbol key console.log (UserID]); / / id value

Example 2:

Let id = Symbol ('id'); let user = {[id]:' id value',// note the square brackets}; console.log (UserID])

The above two examples show the use of inserting a Symbol type as a key in an object, and it is important to note that obj [id] rather than obj.id is required when accessing properties, because obj.id represents obj ['id'].

What if we use Symbol as the key for the object?

For... Skipped in in

A very obvious feature of Symbol is that if Symbol is used as a key in an object, then for is used. In statements do not have access to properties of type Symbol.

For example:

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:

> xiaoming

It can be found that the value of the [id] object is not printed, indicating that in the list of object properties, use for. In automatically ignores keys of type Symbol.

Similarly, Object.keys (user) ignores all keys of type Symbol.

Such features can have very useful effects, for example, we can create properties that can only be used by ourselves.

Although we have no way to get the symbol key directly, the Object.assign method can copy all the properties:

Let id = Symbol (); let obj = {[id]: '123'} let obj2 = Object.assign ({}, obj); console.log (obj2 [id])

This does not affect the hidden properties of Symbol, because the copied object still cannot get the Symbol key.

Hide custom properties

Since Symbol cannot be converted to a string directly, we have no way to get its value intuitively, nor can we use for. In gets the Symbol property of the object, that is, without the Symbol variable itself, there is no way to get the corresponding property inside the object.

Therefore, through the key values of the Symbol type, we can hide the properties, which can only be accessed by ourselves, and no one else can see our properties.

For example:

In the process of development, we need to cooperate with our colleague "Zhang San", and this Zhang San created a very useful tool Tool,Tool is an object type, we want to whore Zhang San's Tool, and add some of our own attributes on this basis.

We can add a key of type Symbol:

Let tool = {/ / Tool usage written by Zhang San: "Can do anything",} let name = Symbol ("My tool obj"); tool [name] = "This is my tool"; console.log (tool [name])

The above example shows how to add your own properties to an object that someone else has written, so why use a Symbol type instead of a regular string?

The reasons are as follows:

Object tool is code written by others. In principle, we should not modify other people's code, which will cause risks.

To avoid naming conflicts, if we use strings directly, it is likely to conflict with other people's original property keys, resulting in serious consequences; naming conflicts will never occur when using Symbol, because Symbol is different.

Others cannot access keys of Symbol type, which means that they will not conflict with other people's code.

Error demonstration:

If we do not use the Symbol type, the following is likely to occur:

Let tool = {/ / Tool usage written by Zhang San: "Can do anything",} tool.usage = "Boom Boom"; console.log (tool.usage)

The above code rewrites the original property due to the repeated use of "usage", which will cause the original function of the object to be abnormal.

Symbol global registry

All Symbol variables are different, even if they use the same tag (description).

Sometimes we want to access the same Symbol object through a string name (label), for example, we access the same Symbol in different parts of the code.

JavaScript maintains a global Symbol registry, which we can access by inserting a Symbol object into the registry and giving the object a string name.

The Symbol.for (key) method is required to insert or read a Symbol object into the registry. If there is an object named key in the registry, it is returned, otherwise a new object is inserted and returned.

For example:

Let id1= Symbol.for ('id'); / / there is no Symbol named id in the registry. Create and return let id2 = Symbol.for (' id'); / / there is already a Symbol named id in the registry, which directly returns console.log (id1===id2); / / true

Instead, we can use Symbol.keyFor (Symbol) to get the name from the object in reverse.

For example:

Let id = Symbol.for ('id'); / / there is no Symbol named id in the registry. Create and return let name = Symbol.keyFor (id); console.log (name); / / id

The Symbol.keyFor () function can only be used on global Symbol objects (objects inserted with Symbol.for), and if used on non-global objects, it returns undefined.

For example:

Let id = Symbol ('id'); / / Local Symbollet name = Symbol.keyFor (id); console.log (name); / / undefined system Symbol

JavaScript has many system Symbol, such as:

Symbol.hasInstance

Symbol.iterator

Symbol.toPrimitive

Each of them has its own use, and we will introduce these unique variables step by step later.

The above is about the "Symbol types of JavaScript, hidden attributes, global registry instance analysis" of this article, I believe we all have a certain understanding, I hope the content shared by the editor will be helpful to you, if you want to know more related knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report