Is there a shorthand way to initialise more than one private instance variable?

前端 未结 1 753
忘掉有多难
忘掉有多难 2021-01-28 07:48

Is there a shorthand way to initialise more than one private instance variable?

class Foo {
    #bar
    #bam
    construc         


        
相关标签:
1条回答
  • 2021-01-28 08:31

    Assuming you are basing your code on the Class field declarations for JavaScript proposal (specifically, private fields):

    There are no private computed property names: #foo is a private identifier, and #[foo] is a syntax error.

    Also see the private syntax FAQ:

    Why doesn't this['#x'] access the private field named #x, given that this.#x does?

    1. This would complicate property access semantics.

    2. Dynamic access to private fields is contrary to the notion of 'private'. E.g. this is concerning:

    class Dict extends null {
      #data = something_secret;
      add(key, value) {
        this[key] = value;
      }
      get(key) {
        return this[key];
      }
    }
    (new Dict).get('#data'); // returns something_secret
    

    But doesn't giving this.#x and this['#x'] different semantics break an invariant of current syntax?

    Not exactly, but it is a concern. this.#x has never previously been legal syntax, so from one point of view there can be no invariant regarding it.

    On the other hand, it might be surprising that they differ, and this is a downside of the current proposal.

    You cannot dynamically access private fields like you can with normal properties. As far as I know, there is thus no way to achieve what you want to do.

    In addition, it seems rather strange that the outside code knows about and tries to define private fields. Maybe you should use get/set instead?

    0 讨论(0)
提交回复
热议问题