Andrey (azangru) wrote,
Andrey
azangru



I am very confused by the javascript private fields syntax.

In typescript, it's sort of intuitive:

class Parent {

  private foo: string;
  protected bar: string;

  constructor() {
    this.foo = 'foo';
    this.bar = 'bar';
  }

  doStuff() {
    return `${this.foo} ${this.bar}`;
  }
  
}

class Child extends Parent {

  // does not inherit foo from parent
  // but does inherit bar from parent

  doStuff() {
    return this.bar;
  }

}


I say "sort of" because, with private fields available only to the instances of the same class and not to the subclasses, the Child class in the example above will inherit the constructor from the parent, in which it will try to assign 'foo' to this.foo, which it isn't supposed to have. I don't know how other languages handle this — they probably ignore it.

In Javascript, however, according to the proposal that is bound to be included in the language, you'll have to prepend an ugly octothorpe to private field names, and then always use the said octothorpe when referencing these fields. Your class will be allowed to have both this.foo (public field) and
this.#foo
(private field). And I can't quite tease out from the proposal whether the subclasses will have access to the private/protected fields of the parents. It looks like they won't. In which case I can't understand why people don't see it as a problem.
Tags: #foo
Subscribe

  • (no subject)

    There's a strange tendency out there for tech podcasters not to be good programmers themselves. There are exceptions, of course. The googlers at…

  • (no subject)

    Achievement unlocked: today, for the first time, I wrote an asynchronous iterator. Using an async generator (also for the first time; I never felt a…

  • (no subject)

    This is a good summation:

  • Post a new comment

    Error

    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments