将符号引入ES6的动机是什么? [英] What is the motivation for bringing Symbols to ES6?

查看:147
本文介绍了将符号引入ES6的动机是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


更新:最近来自Mozilla的精彩文章出现了。如果你很好奇,请阅读它。

UPDATE: Recently a brilliant article from Mozilla came up. Read it if you're curious.

您可能知道它们是计划在ECMAScript 6中包含新的Symbol原始类型(更不用说其他一些疯狂的了)东西)。我一直认为Ruby中的:symbol 概念是不必要的;我们可以轻松地使用纯字符串,就像我们在JavaScript中一样。现在他们决定用JS复杂化JS。

As you may know they are planning to include new Symbol primitive type in ECMAScript 6 (not to mention some other crazy stuff). I always thought that the :symbol notion in Ruby is needless; we could easily use plain strings instead, like we do in JavaScript. And now they decide to complicate things in JS with that.

我不明白动机。有人可以向我解释我们是否真的需要JavaScript中的符号吗?

I don't understand the motivation. Could someone explain to me whether we really need symbols in JavaScript?

推荐答案

将符号引入Javascript的最初动机是启用私人属性。

The original motivation for introducing symbols to Javascript was to enable private properties.

不幸的是,他们最终被严重降级。它们不再是私有的,因为您可以通过反射找到它们,例如,使用 Object.getOwnPropertySymbols 或代理。

Unfortunately, they ended up being severely downgraded. They are no longer private, since you can find them via reflection, for example, using Object.getOwnPropertySymbols or proxies.

它们现在称为唯一符号,它们唯一的用途是避免属性之间的名称冲突。例如,ECMAScript本身现在可以通过某些方法引入扩展钩子,这些方法可以放在对象上(例如定义它们的迭代协议),而不会有与用户名冲突的风险。

They are now known as unique symbols and their only intended use is to avoid name clashes between properties. For example, ECMAScript itself can now introduce extension hooks via certain methods that you can put on objects (e.g. to define their iteration protocol) without risking them to clash with user names.

这是否足够强大,为语言添加符号的动机是值得商榷的。

Whether that is strong enough a motivation to add symbols to the language is debatable.

这篇关于将符号引入ES6的动机是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆