【发布时间】:2020-02-06 09:00:48
【问题描述】:
Node.js 12 支持开箱即用的private class fields denoted by #,没有标志或转译器。
例如,这适用于 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
假设我想构建我的 Foo 实例不是使用 1 个属性,而是使用 20 个属性 - 我必须将构造函数和 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 :-(
我可以使用变量作为标识符来设置私有类字段吗?如果是,如何?
【问题讨论】:
-
为了将来参考,当您问自己如何声明 20 个变量而不重复代码 20 次时,您通常只需要某种集合,例如数组或字典(例如对象或映射) ),如下所示。
-
@PatrickRoberts 我正在尝试使用私有类字段作为创建不可变对象的一种方式,有没有一种优雅的方法可以通过对象或地图来实现这一点?
-
我倾向于拒绝。不过,这正是
Object.freeze()的用途。
标签: javascript node.js private ecmascript-next class-fields