博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[ES6] Symbol
阅读量:5909 次
发布时间:2019-06-19

本文共 1602 字,大约阅读时间需要 5 分钟。

symbol is a unique and immutable data type that is often used to identify object properties.

To create a symbol, you write Symbol() with an optional string as its description.

const sym1 = Symbol('apple');console.log(sym1); // Symbol(apple)

This will create a unique symbol and store it in sym1. The description "apple" is just a way to describe the symbol, but it can’t be used to access the symbol itself.

And just to show you how this works, if you compare two symbols with the same description…

const sym2 = Symbol('banana');const sym3 = Symbol('banana');console.log(sym2 === sym3); // false

 

Example that Symbol can be useful:

const bowl = {  'apple': { color: 'red', weight: 136.078 },  'banana': { color: 'yellow', weight: 183.151 },  'orange': { color: 'orange', weight: 170.097 },  'banana': { color: 'yellow', weight: 176.845 }};console.log(bowl); // Object {apple: Object, banana: Object, orange: Object}

 

Instead of adding another banana to the bowl, our previous banana is overwritten by the new banana being added to the bowl. To fix this problem, we can use symbols.

const bowl = {  [Symbol('apple')]: { color: 'red', weight: 136.078 },  [Symbol('banana')]: { color: 'yellow', weight: 183.15 },  [Symbol('orange')]: { color: 'orange', weight: 170.097 },  [Symbol('banana')]: { color: 'yellow', weight: 176.845 }};console.log(bowl); // Object {Symbol(apple): Object, Symbol(banana): Object, Symbol(orange): Object, Symbol(banana): Object}

By changing the bowl’s properties to use symbols, each property is a unique Symbol and the first banana doesn’t get overwritten by the second banana.

转载地址:http://vkvpx.baihongyu.com/

你可能感兴趣的文章
【反射】使用反射来获取注解原数据信息-类信息-方法信息等
查看>>
当代前端应该怎么写这个hello world?
查看>>
[转载]替代Visio的免费软件:EDraw Mind Map
查看>>
(C#)AJAX post方式传值
查看>>
【转】Installing the libv8 Ruby gem on Centos 5.8
查看>>
【原创】宿主机远程登录虚拟机(windows server 2003系统)
查看>>
【甘道夫】HBase(0.96以上版本号)过滤器Filter具体解释及实例代码
查看>>
HANDLER命令与实现
查看>>
Linux(Centos)之安装tomcat并且部署Java Web项目
查看>>
MySQL中四舍五入的实现
查看>>
单月销量突破300万台,OPPO R9s为何连破纪录?
查看>>
春运第七天 北京西站铁警为“马大哈”旅客找回物品300余件
查看>>
中国2019年基本实现全国建制村直接通邮
查看>>
区块链傻瓜书:EOS与以太坊对比
查看>>
如何设计并实现一个线程安全的 Map ?(上篇)
查看>>
JavaScript的工作原理:解析、抽象语法树(AST)+ 提升编译速度5个技巧
查看>>
react-step-by-step之redux详细注释
查看>>
随手打造一个可以替换全站字符串的nginx镜像(docker)
查看>>
前端开发,关于图片的那些事
查看>>
对于一致性哈希算法的理解
查看>>