繁体   English   中英

我可以使用变量作为标识符来设置私有 class 字段吗? 如何?

[英]Can I set a private class field using a variable as identifier? How?

Node.js 12 支持由# out-of-the-box 表示的私有 class 字段,没有标志或转译器。

例如,这适用于 Node.js 12:

class Foo {
  #bar = 1;

  constructor({ bar }) {
    this.#bar = bar;
  }

  get bar() {
    return this.#bar;
  }
}

const foo = new Foo({ bar: 2 });

console.log(foo.bar); // 2

假设我想用 20 而不是 1 个属性来构造我的 Foo 实例——我必须在构造函数和 getter function 中复制赋值语句 20 次,这会产生很多样板代码。

如果我不使用私有字段,而是使用常规 class 字段,这不难避免:

class Foo {
  bar = 1;

  constructor(properties) {
    Object.entries(properties).forEach(([name, value]) => (this[name] = value));
  }

  get bar() {
    return this.bar;
  }
}

const foo = new Foo({ bar: 2 });

console.log(foo.bar); // 2

但是,对于私有 class 字段,它不起作用:

class Foo {
  #bar = 1;

  constructor(properties) {
    Object.entries(properties).forEach(
      ([name, value]) => (this[`#${name}`] = value)
    );
  }

  get bar() {
    return this.#bar;
  }
}

const foo = new Foo({ bar: 2 });

console.log(foo.bar); // 1 :-(

我还尝试使用 Reflect.set 为构造函数中的私有class字段分配一个值,但无济于事:

class Foo {
  #bar = 1;

  constructor(properties) {
    Object.entries(properties).forEach(([name, value]) =>
      Reflect.set(this, `#${name}`, value)
    );
  }

  get bar() {
    return this.#bar;
  }
}

const foo = new Foo({ bar: 2 });

console.log(foo.bar); // 1 :-(

我可以使用变量作为标识符来设置私有 class 字段吗? 如果是,如何?

不,这看起来不可能。 提案常见问题解答

为什么 this['#x'] 不访问名为 #x 的私有字段,因为 this.#x 可以?

  1. 这会使属性访问语义复杂化。

  2. 对私有字段的动态访问与“私有”的概念相反。 例如,这是关于:

 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

语法是这样的,每个私有字段都必须在文字属性名称之前用#进行初始化和/或引用,仅此而已。 甚至不允许使用括号表示法。

拥有一个名为 x 的私有字段不能阻止有一个名为 x 的公共字段,因此访问私有字段不能只是正常的查找。

You can't even reference a private field unless it's explicitly defined in the class body ( not a class function, but inside the class body directly):

 class Foo { // error is thrown because #abc must be defined in this section doSomething() { return this.#abc; } }

也就是说,没有什么能阻止您创建一个私有属性object ,所有这些属性都在 object 上:

 class Foo { #privates = {}; constructor(properties) { Object.entries(properties).forEach( ([name, value]) => (this.#privates[name] = value) ); } get privates() { return this.#privates; } } const foo = new Foo({ bar: 2 }); console.log(foo.privates.bar);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM