Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript’s Symbol type, hidden attributes and global registry

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

WBOY
WBOYforward
2022-06-02 11:50:342678browse

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.net. If there is any infringement, please contact admin@php.cn delete