在类构造函数 (ES6) 中定义常量

Define a const in class constructor (ES6)

本文关键字:定义 常量 ES6 构造函数      更新时间:2023-09-26

有没有办法在类的构造函数中定义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() );