我可以使用变量作为标识符来设置私有类字段吗?怎么样?
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 :-(
我可以使用变量作为标识符来设置私有类字段吗?如果是,如何?
Node.js 12支持开箱即用#表示的私有类字段,没有标志或编译器。例如,这适用于Node.js 12:class Foo {#bar = 1;构造函数({bar}){...
回答如下:不,这看起来不可能。从proposal FAQ:
我可以使用变量作为标识符来设置私有类字段吗?怎么样?
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 :-(
我可以使用变量作为标识符来设置私有类字段吗?如果是,如何?
Node.js 12支持开箱即用#表示的私有类字段,没有标志或编译器。例如,这适用于Node.js 12:class Foo {#bar = 1;构造函数({bar}){...
回答如下:不,这看起来不可能。从proposal FAQ: