Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a const in class constructor (ES6) [duplicate]

Is there a way I can define a const in the constructor of a class?

I tried this:

class Foo {
    constructor () {
        const bar = 42;
    }

    getBar = () => {
        return this.bar;
    }
}

But

var a = new Foo();
console.log ( a.getBar() );

returns undefined.

like image 589
alexandernst Avatar asked Feb 06 '16 14:02

alexandernst


1 Answers

You use static read-only properties to declare constant values that are scoped to a class.

class Foo {
    static get BAR() {
        return 42;
    }
}

console.log(Foo.BAR); // print 42.
Foo.BAR = 43; // triggers an error
like image 61
Reactgular Avatar answered Nov 05 '22 07:11

Reactgular