Live data from Hacker News

Public and private class fields

developers.google.com

1–10 of 112 posts

Re: Public and private class fields

#3
This syntax is...odd. It is not expressive and comes off as a "language hack." The only people who would understand it are those who happen to stumble on this article.

Frankly, if this is an issue that you are concerned about, you should really invest the time to learn (and possibly migrate to) TypeScript. Specifically, see their class documentation which already has support for `public`, `private`, and `protected` [1]. (Edit: read @denisw's reply regarding TS. I make this suggestion specifically for TS's compile-time assistance regarding private field access.)

It actually kind of boggles my mind that V8 engineers sat down and agreed that this would be a good design decision. Granted, the article says that they are proposals—is there any way to provide feedback on this? (Edit: https://github.com/tc39/proposal-class-fields/blob/master/PR...)

[1] https://www.typescriptlang.org/docs/handbook/classes.html

Re: Public and private class fields

#5
This is Exhibit N for the "the class keyword is ruining Javascript" prosecution. If you want a "private variable" you just use a closure.

  let incrementer = () =>  { 
     let x = 0; 
     return { value: () => x, increment: () => x++ }; 
  };
It's like the OO people are determined to forget about the functional concepts that made JS great.

Re: Public and private class fields

#6
post #5

This is Exhibit N for the "the class keyword is ruining Javascript" prosecution. If you want a "private variable" you just use a closure. let incrementer = () => { let x = 0; return { value: () => x, increment: () => x++ }; }; It's like the OO people are determined to forget about the functional concepts that made JS great.

I agree.

Re: Public and private class fields

#9
post #5

This is Exhibit N for the "the class keyword is ruining Javascript" prosecution. If you want a "private variable" you just use a closure. let incrementer = () => { let x = 0; return { value: () => x, increment: () => x++ }; }; It's like the OO people are determined to forget about the functional concepts that made JS great.

I was in the process of writing a reply that argued against this (mainly because it is not as readable as a class implementation), but I sort of agree with you as well.

That said, considering how widespread JavaScript is at this point, I think it is in their best interest to cater to more than one programming style.

Re: Public and private class fields

#10
post #8

I don't understand why public fields need the underscore prefix. Aren't all fields public by default? Why do you need to add a prefix to "hide" public fields?

They don't, that's just the example they chose. Prefixing variables / functions with the underscore has long been a signal for "this is private" in languages that don't provide the functionality.
Post reply on HN