在类构造函数 (ES6) 中定义常量
Define a const in class constructor (ES6)
有没有办法在类的构造函数中定义const
?
我试过这个:
class Foo {
constructor () {
const bar = 42;
}
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
进行设置。我猜你想要不可变性,所以你可以使用 getters:
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
时引发错误。如果需要,您可以在二传器中引发错误:
class Foo {
constructor () {
this._bar = 42;
}
get bar() {
return this._bar;
}
set bar(value) {
throw new Error('bar is immutable.');
}
}
问题出在"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() );
相关文章:
- 使用在子模块内部的父模块上定义的常量's配置
- 将常量或变量的值定义为不带赋值的常量或变量名称
- 在 ecma-script-6 中将对象定义为常量
- 在类构造函数 (ES6) 中定义常量
- 导入的常量未定义
- 如何在 javascript 中创建自定义对象的通用常量实例
- AngularJS module.constant() :如何仅在模块内定义常量
- 未定义的AngularJS常量不是对象
- 如何通过原型定义常量
- JavaScript:使用严格模式在try/catch中定义一个常量
- 常量在一个服务中未定义,但在另一个服务中有效
- 在angularjs中为常量定义函数
- 为什么在实例模式下使用p5.js时没有定义常量?
- 如何定义“常量”并在NodeJS中随处访问它
- 在es6类中为angular 1.5控制器定义常量
- 正在生成定义常量的JS代码,被认为是不好的做法
- NodeJs定义全局常量
- AngularJS常量没有定义
- HTML/CSS/JavaScript是否定义了表示系统主题颜色的常量
- “未定义的常量/变量”错误使用带有 Angular JS的 Laravel...无法在边栏选项卡中显示变量