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

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

问题描述

更新:最近一篇精彩文章来自 Mozilla 出现了.如果您好奇,请阅读它.

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

你可能知道它们是 计划在 ECMAScript 6 中包含 新的 Symbol 原始类型(更不用说其他一些疯狂的东西).我一直认为 Ruby 中的 :symbol 概念是不必要的;我们可以轻松地使用普通字符串代替,就像我们在 JavaScript 中所做的那样.现在他们决定让 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.

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

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