为什么带符号到javascript? [英] Why bring symbols to javascript?
问题描述
:符号
概念是不必要的;我们可以轻松地使用简单的字符串,就像我们在JavaScript中一样。而现在他们决定在JS中使事情复杂化。 我不明白动机。有人可以向我解释我们是否真的需要JavaScript中的符号?
更新:最近一个来自Mozilla的精彩文章。如果你好奇,请阅读它。
启用私有属性,如在他的答案中描述的kangax,确实是原来的动机将符号引入JavaScript。
然而,不幸的是,他们最终被严重降级,而不是私有的,因为您可以通过反思找到它们。具体来说,通过 Object.getOwnPropertySymbols
方法和代理。
它们现在被称为唯一符号,它们唯一的用途是避免属性之间的名称冲突。例如,EcmaScript本身现在可以通过某些可以放在对象上的方法引入扩展钩子(例如定义它们的迭代协议),而不会产生与用户名冲突的风险。
无论是足够强大的动机,为语言添加符号是有争议的。
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.
I don't understand the motivation. Could someone explain to me whether we really need symbols in JavaScript?
UPDATE: Recently a brilliant article from Mozilla came up. Read it if you're curious.
Enabling private properties, like kangax describes in his answer, was indeed the original motivation for introducing symbols into JavaScript.
Unfortunately, however, they ended up being severely downgraded, and not private after all, because you can find them via reflection. Specifically, via the Object.getOwnPropertySymbols
method and through proxies.
They are now known as unique symbols, and their only use is to avoid name clashes between properties. For example, EcmaScript itself can now introduce extension hooks via certain methods you can put on objects (e.g. to define their iteration protocol) without running the risk of clashing with user names.
Whether that is strong enough a motivation to add symbols to the language is debatable.
这篇关于为什么带符号到javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!