search
HomeWeb Front-endJS TutorialDetailed 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.

Detailed explanation of JavaScript's Symbol type, hidden attributes and global registry

[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 a

Symbol 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
The 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

type in

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.

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 obtain description information:

let id = Symbol('加油,奥利给');
console.log(id.description);//加油,奥利给”
Symbol is similar to the property key of an object

According to the specifications of

JavaScript, there are only two types The value can be used as the attribute key of the object:

    String
  1. Symbol
If other types are used, they will be implicitly converted to strings type. Object keys are introduced in detail in previous chapters 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';//添加Symbol键
console.log(user[id]);//id value
Example 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'].

What will be the effect if we use

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.

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 comes out, indicating that in the object attribute list, using for ... in will automatically ignore keys of type Symbol.

Similarly,

Object.keys(user) will also ignore all Symbol type keys.

Such a feature can bring very useful effects, for example, we can create attributes that can only be used by ourselves.

Although we have no way to directly obtain the

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既不能直接转为字符串,我们没有办法直观的获得它的值,又不能通过for … in获得对象的Symbol属性,也就是说,如果没有Symbol变量本身,我们就没有办法获得对象内部的对应属性。

因此,通过Symbol类型的键值,我们可以隐藏属性,这些属性只能我们自己访问,其他人都看不到我们的属性。

举个例子:

我们在开发的过程中,需要和同事“张三”合作,而这个张三创建了一个非常好用的工具ToolTool是一个对象类型,我们想白嫖张三的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类型而不是常规的字符串呢?

原因如下:

  1. 对象tool是别人写好的代码,原则上我们不应该去修改别人的代码,这样会造成风险;
  2. 避免命名冲突,我们直接使用字符串很有可能会和别人原有的属性键冲突,造成严重的后果;
  3. 使用Symbol永远不会发生命名冲突,因为Symbol都是不同的;
  4. 别人无法访问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

它们各有用途,我们在后面的会逐步介绍道这些独特的变量。

总结

  1. Symbol对象的值是唯一的;
  2. Symbol可以添加一个标签,并通过标签在全局注册表中查询对象的实体;
  3. Symbol作为对象的键无法被for … in探测到;
  4. 我们可以通过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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software