Node.js 12 支持由# out-of-the-box 表示的私有类字段,没有标志或转译器。
例如,这适用于 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 函数中的赋值语句复制 20 次,这会产生很多样板代码。
如果我不使用私有字段而是使用常规类字段,这不难避免:
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 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 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 :-(
我可以使用变量作为标识符来设置私有类字段吗?如果是,如何?