我能否在类的构造函数中定义一个 const
常量?
我尝试过以下方法:
class Foo {
constructor () {
const bar = 42;
}
getBar = () => {
return this.bar;
}
}
但是
var a = new Foo();
console.log ( a.getBar() );
返回undefined。
我能否在类的构造函数中定义一个 const
常量?
我尝试过以下方法:
class Foo {
constructor () {
const bar = 42;
}
getBar = () => {
return this.bar;
}
}
但是
var a = new Foo();
console.log ( a.getBar() );
返回undefined。
您可以使用静态只读属性来声明作用于类的常量值。
class Foo {
static get BAR() {
return 42;
}
}
console.log(Foo.BAR); // print 42.
Foo.BAR = 43; // triggers an error
=>
不应该在那里。 - alexandernst仅在构造函数中定义一个常量不会将其附加到实例上,您必须使用this
来设置它。我猜想您想要不可变性,因此可以使用getter:
class Foo {
constructor () {
this._bar = 42;
}
get bar() {
return this._bar;
}
}
然后您可以像平常一样使用它:
const foo = new Foo();
console.log(foo.bar) // 42
foo.bar = 15;
console.log(foo.bar) // still 42
在尝试更改bar
时,这不会引发错误。如果您想要,在setter中可以引发错误:
class Foo {
constructor () {
this._bar = 42;
}
get bar() {
return this._bar;
}
set bar(value) {
throw new Error('bar is immutable.');
}
}
'use strict';
class Foo {
constructor () {
const bar = 42;
this.bar = bar; // scoping to the class
}
getBar () {
return this.bar;
}
}
var a = new Foo();
console.log ( a.getBar() );
const
的属性,对吧? - alexandernstthis.bar
不会是一个常量,它可以被覆盖。 - adeneoconst
不能在类中使用,它到底有什么意义呢? - alexandernstconst
关键字是 var
的不可变版本,具有与 var
相同的作用域问题。 - Reactgular