ale*_*nst 9 javascript ecmascript-6
有没有办法const在类的构造函数中定义一个?
我试过这个:
class Foo {
constructor () {
const bar = 42;
}
getBar = () => {
return this.bar;
}
}
Run Code Online (Sandbox Code Playgroud)
但
var a = new Foo();
console.log ( a.getBar() );
Run Code Online (Sandbox Code Playgroud)
返回undefined.
Rea*_*lar 18
您可以使用静态只读属性来声明作用于类的常量值.
class Foo {
static get BAR() {
return 42;
}
}
console.log(Foo.BAR); // print 42.
Foo.BAR = 43; // triggers an error
Run Code Online (Sandbox Code Playgroud)
只需在构造函数中定义一个常量就不会将其附加到实例,您必须使用进行设置this。我猜你想要不变性,所以可以使用getters:
class Foo {
constructor () {
this._bar = 42;
}
get bar() {
return this._bar;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像平常一样使用它:
const foo = new Foo();
console.log(foo.bar) // 42
foo.bar = 15;
console.log(foo.bar) // still 42
Run Code Online (Sandbox Code Playgroud)
尝试更改时,这不会引发错误bar。如果需要,可以在设置器中引发错误:
class Foo {
constructor () {
this._bar = 42;
}
get bar() {
return this._bar;
}
set bar(value) {
throw new Error('bar is immutable.');
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12096 次 |
| 最近记录: |