Javascript 在类构造函数(ES6)中定义常量
有没有办法在类的构造函数中定义一个Javascript 在类构造函数(ES6)中定义常量,javascript,ecmascript-6,Javascript,Ecmascript 6,有没有办法在类的构造函数中定义一个const 我试过这个: class Foo { constructor () { const bar = 42; } getBar = () => { return this.bar; } } 但是 返回未定义。问题在于“bar”作用域-其作用域为构造函数: 'use strict'; class Foo { constructor () { const bar
const
我试过这个:
class Foo {
constructor () {
const bar = 42;
}
getBar = () => {
return this.bar;
}
}
但是
返回未定义。问题在于“bar”作用域-其作用域为构造函数:
'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() );
您可以使用静态只读属性来声明作用于类的常量值
class Foo {
static get BAR() {
return 42;
}
}
console.log(Foo.BAR); // print 42.
Foo.BAR = 43; // triggers an error
简单地在构造函数中定义一个常量不会将其附加到实例,您必须使用
this
设置它。我猜你想要不变性,所以你可以使用:
然后您可以像平常一样使用它:
const foo = new Foo();
console.log(foo.bar) // 42
foo.bar = 15;
console.log(foo.bar) // still 42
当尝试更改条时,这不会引发错误。如果需要,可以在setter中引发错误:
class Foo {
constructor () {
this._bar = 42;
}
get bar() {
return this._bar;
}
set bar(value) {
throw new Error('bar is immutable.');
}
}
啊,我明白了。这样做,将保持const
的属性,对吗?@alexanderst-不,this.bar
将不是常数,如果不能在类中使用,const
有什么意义呢?我正在写另一个答案,可能更接近你想要的…@alexandernstconst
关键字是var
的一个不可变版本,并且与var
具有所有相同的范围问题。实际上,=>
不应该在那里。@alexandernst谢谢。@Bergi与我所问的一点也不相似。很好地解释了变量和属性之间的区别,您似乎遇到了问题。诚然,它没有告诉您如何定义不可写属性。
const foo = new Foo();
console.log(foo.bar) // 42
foo.bar = 15;
console.log(foo.bar) // still 42
class Foo {
constructor () {
this._bar = 42;
}
get bar() {
return this._bar;
}
set bar(value) {
throw new Error('bar is immutable.');
}
}