Home > Article > Web Front-end > 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 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 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);//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.
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);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:
Symbol 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?
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
既不能直接转为字符串,我们没有办法直观的获得它的值,又不能通过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
。
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
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!