Define const constructor in class (ES6)

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

I tried this:

 class Foo { constructor () { const bar = 42; } getBar = () => { return this.bar; } } 

But

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

returns undefined.

+5
source share
3 answers

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

 class Foo { static get BAR() { return 42; } } console.log(Foo.BAR); // print 42. Foo.BAR = 43; // triggers an error 
+14
source

Just defining a constant in the constructor will not attach to the instance, you have to set it with this . I assume you want immutability, so you can use getters :

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

Then you can use it as usual:

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

This will not cause an error when trying to change bar . You can make a mistake in the setter if you want:

 class Foo { constructor () { this._bar = 42; } get bar() { return this._bar; } set bar(value) { throw new Error('bar is immutable.'); } } 
+1
source

The problem with the "bar" area is that it is bound to the 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() ); 
0
source

Source: https://habr.com/ru/post/1242439/


All Articles