Is there a convention for naming symbols in ES6?

人盡茶涼 提交于 2020-02-03 05:57:56

问题


I'm toying around with ES6, looking at symbols. Unlike ruby for example where you'd write :symbol, ES6 symbols seem to be allowed any "standard" variable name. To be honest I am finding this rather confusing:

var privateProperty = Symbol();
var obj = {};
obj[privateProperty] = 'some value goes here';

as it tends to make me think that privateProperty is probably a plain string like the years before. Using :privateProperty is not valid.

So just like using $bar for a jQuery object or bar$ for a RxJS/Bacon stream, I was wondering if there is already an established convention for naming symbols in ES6?


回答1:


obj[privateProperty] = …; tends to make me think that privateProperty is probably a plain string like the years before.

Well, that's the old thinking that we will need to forget. privateProperty is a key, which can be either a string (property name) or symbol. Similarly, we already have learned to distinguish (integer) indices from "normal" properties.

ES6 seems to allow any "standard" variable name

Just as does Ruby. The difference is that ES6 doesn't introduce a literal notation for symbols (which resolve to the same thing), but allows them to be created only by using Symbol (locally) or Symbol.for (globally).

There is no standard convention for naming variables that hold symbol values.
Of course, you can always use hungarian notation if you tend to want such type annotations. If I had to coin a standard, I'd propose to use a more subtle leading underscore (var _myPrivate). Underscores in property names had always implied something special, and it would look similar for computed property keys (obj[_myPrivate]) then.

Is there a convention for naming symbols in ES6?

While there is no convention for naming symbol-holding variables (yet), there certainly is a convention for naming symbols themselves:

  • local symbols should have a very descriptive descriptor string (given as an argument to Symbol). Of course, they're still unique anyway, so you basically can use whatever name you want.
  • global symbols need to avoid collisions. The convention is to namespace them appropriately, and connect those namespace names with dots - like a Java package name. If the symbol is available as a global variable, its descriptor should have the same name (similar to the builtin, native symbols, which are like @@iterator = Symbol.for("Symbol.iterator");). If the symbol is exported by a module or library, its descriptor should be prefixed with the module/library name (to avoid collisions).

And it would probably be a best practise to use the same name for the variable (like the native symbols already do, Symbol.iterator.toString() == "Symbol(Symbol.iterator)").



来源:https://stackoverflow.com/questions/31356968/is-there-a-convention-for-naming-symbols-in-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!