ECMAScript 6中的符号(字符串) [英] Symbol.for(string) in ECMAScript 6

查看:155
本文介绍了ECMAScript 6中的符号(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一段时间,但我终于弄清了ECMAScript 6中符号的目的是:在将属性附加到共享对象时避免名称冲突 - HTML元素,例如(如果您遇到同样的问题,我建议您这篇文章。 )



但是,我偶然发现了 Symbol.for()符号/。显然,ECMAScript 6将维护一个全局符号注册表,您可以通过提供符号描述来查询此功能。再来?如果我使用符号来避免名称冲突,为什么我要使用我自己的代码来使用它们? (*)我如何避免在全球注册表中的名称冲突?符号的共享似乎完全颠覆了这个概念和一个全局注册表,所以这样。



(*)是的,我知道符号不是真正的私人的,但这除了这一点。

解决方案

如果您不希望在GlobalSymbolRegistry中提供您的符号,请使用 Symbol.for



只有在要允许其他代码使用您的符号时才可使用它。 / p>

在以下示例中,我创建一个符号来存储DOM元素中的数据。而且我可能想要其他所有的代码(例如内部未编译的处理程序)读取数据。所以我使符号全球可用。



  var sym = Symbol.for('storeDataInDOM'); document.querySelector('button')[ sym] ='Hello,world!';  

  button onclick =alert(this [Symbol.for('storeDataInDOM')])>点击我< / button>  

/ p>

这就像创建全局变量:一般应该避免,但有其优点。但是用符号而不是字符串。


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.)

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.

解决方案

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.

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中的符号(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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