ECMAScript 6 中的 Symbol.for(string) [英] Symbol.for(string) in ECMAScript 6
问题描述
我花了一段时间,但我终于弄清楚了 ECMAScript 6 中符号的目的是什么:在将属性附加到共享对象时避免名称冲突 - HTML 元素,例如(如果您遇到同样的问题,我推荐这篇文章.)
It took me a while but I finally figured out what the purpose of symbols in ECMAScript 6 is: avoiding name collision when attaching properties to shared objects - HTML elements e.g. (In case you're stuck on the same question, I recommend this article.)
但后来我偶然发现了Symbol.for().显然 ECMAScript 6 将维护一个全局符号注册表,您可以通过提供符号描述来使用此函数进行查询.再来?如果我使用符号来避免名称冲突,我为什么要使用我自己以外的代码来使用它们?(*) 我将如何避免该全局注册表中的名称冲突?符号的共享似乎完全颠覆了这个概念,而全球注册也是如此.
But then I stumbled upon Symbol.for(). Apparently ECMAScript 6 will maintain a global symbol registry which you can query with this function by providing the symbol description. Come again? If I use symbols to avoid name collisions, why would I want code other than my own to use them? (*) And how would I avoid name collisions in that global registry? Sharing of symbols seems to completely subvert the concept and a global registry doubly so.
(*) 是的,我知道符号不是真正私有的,但这不是重点.
(*) Yes, I know symbols aren't truly private, but that's besides the point.
推荐答案
如果您不希望您的符号在 GlobalSymbolRegistry 中可用,请不要使用 Symbol.for
.
If you don't want your symbols to be available in GlobalSymbolRegistry, just don't use Symbol.for
.
仅当您想让其他代码使用您的符号时才使用它.
Only use it if you want to allow other codes to use your symbol.
在下面的示例中,我创建了一个符号来在 DOM 元素中存储数据.我可能想要所有其他代码(例如 内部原始未编译处理程序)读取该数据.所以我让符号全局可用.
In the following example, I create a symbol to store data in DOM elements. And I may want every other code (e.g. internal raw uncompiled handlers) to read that data. So I make the symbol globally available.
var sym = Symbol.for('storeDataInDOM');
document.querySelector('button')[sym] = 'Hello, world!';
<button onclick="alert(this[Symbol.for('storeDataInDOM')])">Click me</button>
这就像创建全局变量:一般应该避免,但有其优点.但是用符号代替字符串.
It's like creating global variables: should be avoided in general, but has its advantages. But with symbols instead of strings.
这篇关于ECMAScript 6 中的 Symbol.for(string)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!