15

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.

alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • 1
    @Bergi Not even remotely similar to what I'm asking. – alexandernst Feb 06 '16 at 16:50
  • Well [it](http://stackoverflow.com/questions/13418669/javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) explains the difference between variables and properties, with which you seem to have problems. Admittedly, it doesn't tell it you how to define nonwritable properties. – Bergi Feb 06 '16 at 17:22

3 Answers3

30

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
Reactgular
  • 52,335
  • 19
  • 158
  • 208
8

Simply defining a constant in the constructor won't attach it to the instance, you have to set it using this. I'm guessing you want immutability, so you can use getters:

class Foo {
    constructor () {
        this._bar = 42;
    }

    get bar() {
        return this._bar;
    }
}

Then you can use it like you normally would:

const foo = new Foo();
console.log(foo.bar) // 42
foo.bar = 15;
console.log(foo.bar) // still 42

This will not throw an error when trying to change bar. You could raise an error in a setter if you want:

class Foo {
    constructor () {
        this._bar = 42;
    }

    get bar() {
        return this._bar;
    }

    set bar(value) {
        throw new Error('bar is immutable.');
    }
}
silvenon
  • 2,068
  • 15
  • 29
0

The problem is with "bar" scoping - it scoped to constructor:

'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() );
Oleksii
  • 233
  • 2
  • 6