1

Similar to a question I had some time back: Private properties in JavaScript ES6 classes

This question has more to do with the emergence of using WeakMaps and Symbols to store private variables. Since I would be declaring any private member structures at the top of the file, wouldn't this require a function closure around all of it?

const _color = Symbol('color');
class colorPicker {
  constructor(color) {
    this[_color] = color;
  }
}

The _color is now gonna be in the window namespace, even if not hoisted. Is this proper ? or should the IIFE be wrapped around it?

Seems like ECMA may have missed something with this? Or do they intend to actually use private and public reserved keywords in ESNext?

Community
  • 1
  • 1
webdevinci
  • 301
  • 3
  • 10
  • Maybe [`Symbol.for()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for) is what you're looking for? That creates a symbol if not extant, or gets a symbol if already created, at a runtime level. Obviously, since it's runtime scoped, you'll probably want to use a longer string than 'color'... – Heretic Monkey Jul 05 '16 at 21:57
  • They will be module-scoped, so there is no reason to create another scopes with either IIFE or a `{ ... }` block. "The _color is now gonna be in the window namespace, even if not hoisted" --- why do you think so? – zerkms Jul 05 '16 at 22:47
  • 1
    Symbols are not private. – Bergi Jul 06 '16 at 00:05
  • @zerkms : I guess I didn't think about const / let not getting hoisted to the window namespace. I believe that is the answer I am looking for: **If the Symbol or WeakMap used for private variables is stored in a const/let, it won't get attached as a window property, even when not in a closure/block.** – webdevinci Jul 06 '16 at 15:17
  • @Bergi : The Symbol itself isn't private, but it looks like the contents of it are. – webdevinci Jul 06 '16 at 15:17
  • @webdevinci: No, everybody can access any symbol properties of an object he is holding. – Bergi Jul 06 '16 at 15:36

0 Answers0