7 ms·
Implementing Private Fields for JavaScript
- caymanjim 5y agoHopefully they come up with something better than a # prefix for identifying private fields. It seems like a small thing, but it looks clunky and arbitrary. Even _ would be better, but best of all would be adding a keyword or something instead of using a glyph.
- v413 5y agoThe # symbol denoting private fields has already been finalized and approved to be a legal part of the language. No going back.
- the_other 5y agoFor some time, there was a trend of adding _ to property and method names to indicate “I’m pretending to be private, don’t use me” (I think this happens in several languages, but I only know JS well). I suspect there’s a risk that if the committee standardised on _ rather than #, it would actually break a load of older apps and content. There’s a good chance the _convention was abused in those earlier codebases.
- unwind 5y agoAs far as I know it's the standard way in Python.
- andy_ppp 5y agoWhy can’t they just introduce a new private keyword, i.e. private let myVar = 0;
- ezekg 5y agoThe proposal doesn’t even know.
- Madeindjs 5y ago> `_` would cause compatibility issues with existing JavaScript code, which has allowed `_` at the start of an identifier or (public) property name for a long time. -- https://github.com/tc39/proposal-private-fields/blob/master/FAQ.md https://github.com/tc39/proposal-private-fields/blob/master/...
- nobody0 5y agoYes, _ is much better given its precenses in other languages. I would associate # with a number or a link.
- nikolay 5y agoThe semantic meaning of "#name" is not private. In fact, the "_" is much more meaningful than "#", which is always used as in the meaning of "number" or "index".
- ssdspoimdsjvv 5y agoOne more reason to just use Typescript.
- andy_ppp 5y agoVariables are never truly private in the compiled JS though. You can fake it using clever closure techniques but there are still ways to access the vars as I understand it. This is fixing that at the JS level.
- tylerhou 5y agoI don’t know of any way of accessing lexically bound variables that are captured by a closure if there is no explicit getter.
- throw_m239339 5y agoTypescript is a mostly superset of javascript. Typescript does/will also support # for private fields so it changes absolutely nothing.
- elondaits 5y agoThis is all covered here: https://github.com/tc39/proposal-private-fields/blob/master/FAQ.md https://github.com/tc39/proposal-private-fields/blob/master/...
- cutler 5y agoBetter would be priv.
- nikolay 5y agoThis is exactly what I came up with, too, because it follows "constant => const" analogy. Why are constants not "$name" using the same perverted logic?!
- dmitriid 5y agoI'm still miffed that private fields are not marked with `private`. Can't remember the reasons though.
- fossilwater 5y agoHere’s what they said in the proposal https://github.com/tc39/proposal-private-fields/blob/master/FAQ.md https://github.com/tc39/proposal-private-fields/blob/master/...
- tgv 5y agoNot convincing. When you add a new feature, you can change the parser. So internally, you could rewrite every usage of this.x to this.#x (or anything else) upon reading it. Edit: wrt encapsulation, will the proposed solution work when a class marks the same field private as the one it extends?
- minitech 5y agoBreaking this.x being equivalent to this['x'], and making this.x quietly change its meaning depending on where the function containing it is located and on the presence or absence of a private field with a corresponding name, seems confusing.
- TazeTSchnitzel 5y agoI'm surprised they're adding private fields when symbols already exist? Is it just for improved convenience?
- v413 5y agoObject properties defined as Symbols (even through classes) are still accessible by e.g. Object.getOwnPropertyDescriptors(myObject) Before the private fields, it was possible to create private properties through a WeakMap object which is somewhat clumsy and not very performant.
- SPBS 5y agoI don't understand why people are so hyped about OOP syntactic sugar when JavaScript could already do those ages ago. For example: the class keyword. JavaScript could already do classes via factory functions (return an object with associated methods), and factory functions are strictly more powerful than classes because you can declare freestanding variables inside. And here's the kicker: The freestanding variables that you do declare inside a factory function, those are naturally private fields. You can expose it to the outside world via method closures, but no one else can reach in and modify it directly. Classes can't do that. Functions could. But the general sentiment is to embrace classes and throw factory functions to the wayside, and as a result you need extra effort like implementing private fields for classes when JavaScript functions can already do the same thing.
- tgv 5y agoBecause syntactic sugar matters. var x = (function(){})() is just not readable, but it is error prone. The same goes for assigning to __proto__. IMO, the class keyword is a step forward. However, adding # to a variable looks like a step backward. How long before we have this.%x, to mark x "protected"? Or get x() {...} vs set #x()?
- SPBS 5y agoFactory functions don't mean using the (admittedly ugly) IIFE syntax or accessing __proto__ fields. This is an example of factory function function NewObj(n) { let myPublicInt = n; let myPrivateInt = 0; function privateIncrement() { myPrivateInt++; } function incrementPrivateInt() { privateIncrement(); } function printPrivateInt() { console.log(myPrivateInt); } return { myPublicInt, incrementPrivateInt, printPrivateInt, }; } let obj = NewObj(5); console.log(obj.myPublicInt); // 5, because myPublicInt is a public field console.log(obj.myPrivateInt); // undefined, because myPrivateInt is a private field // obj.privateIncrement(); // exception, because privateIncrement is a private method obj.printPrivateInt(); // 0 obj.incrementPrivateInt(); obj.printPrivateInt(); // 1
- 5y ago
- miohtama 5y agoAre private fields worth all of the problems, as mentioned in article, in a language like JavaScript? Looks like it is cramming in little needed feature with some runtime cost. Also the mental model of private fields does not seem to map to JavaScript constructs very well. Are there any obvious advantages as vast better JIT performance, etc Edit: Sounds very confusing and overengineered > Having a private field named x must not prevent there from being a public field named x, so accessing a private field can't just be a normal lookup.
- fallingknife 5y agoYeah, I don't get it. Just start the name with a _ and don't allow code that calls it from outside the class.
- austincheney 5y agoPrivate class properties have been highly requested for nearly a decade since classes were first mentioned as a part of ES6, since almost after ES5 was formally published. This is wanted to make the language more friendly to CS graduates and Java developers who are otherwise not comfortable using the language without the OOP they cannot live without outside this language. As an example, when I have had discussions about this in the past most proponents had no idea how scope works in the language.
- kkirsche 5y agoI appreciate the context here, though I strongly dislike the reason. One of the values, in my opinion, of learning and working with multiple languages is being exposed to new paradigms and concepts rather than relying on a single approach to solving problems. At its core, javascript is a procedural language, with many functional concepts, and the more we try to hide the prototype-based underpinnings, I think it hurts this growth opportunity. With that said, JS is a mess in a lot of ways, so maybe this is worthwhile. Hard to know though until it’s too late to revert. Just my opinion though, I’m curious what others think about this and where I may be missing the mark.
- zanethomas 5y ago
- flefto 5y agoI don’t believe in private variables/fields. They shouldn’t be used or implemented. A waste of time and effort.
- zanethomas 5y agoI wish they would just leave javascript alone and continue with java or c# or c++ or whatever it is they are trying to transfrom javascript into.
- Aardwolf 5y agoI'm wondering if this should be made part of the runtime at all, and not instead e.g. enforce this by JS compilers/minifiers/style checkers: this is something that's relevant at development time, but not at runtime
- IshKebab 5y agoI agree. Given we already have this in Typescript it seems of little benefit to add it as a runtime feature.
- nikolay 5y agoInsanely ugly syntax, which breaks the cleanness of JavaScript! I don't buy their rationale - JavaScript is not the only language with private fields, but one of the few it decided to use meaningless prefixes!