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)

    Tweeted and retweeted by developers. Dunno. Been working for me. Can't speak to excellence, but certainly lots of stimulating humiliation:

  • (C)opied from Twitter

    Don't know if this is real or not, but if it is, it's really strange that Canadian bureaucrats should be specifically instructed not to use the…

  • (no subject)

    This was a good talk. Interesting to see that SvelteKit is taking the same direction as Remix.run, by using html forms to submit data without the…

  • 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