Declaring Static Constants in Es6 Classes

Declaring static constants in ES6 classes?

Here's a few things you could do:

Export a const from the module. Depending on your use case, you could just:

export const constant1 = 33;

And import that from the module where necessary. Or, building on your static method idea, you could declare a static get accessor:

const constant1 = 33,
constant2 = 2;
class Example {

static get constant1() {
return constant1;
}

static get constant2() {
return constant2;
}
}

That way, you won't need parenthesis:

const one = Example.constant1;

Babel REPL Example

Then, as you say, since a class is just syntactic sugar for a function you can just add a non-writable property like so:

class Example {
}
Object.defineProperty(Example, 'constant1', {
value: 33,
writable : false,
enumerable : true,
configurable : false
});
Example.constant1; // 33
Example.constant1 = 15; // TypeError

It may be nice if we could just do something like:

class Example {
static const constant1 = 33;
}

But unfortunately this class property syntax is only in an ES7 proposal, and even then it won't allow for adding const to the property.

How do I use a static variable in ES6 class?

Your class has no static variables (if by static variable you mean static property). getCount returns NaN (after you call increaseCount) because Animal has no count property initially. Then increaseCount does undefined + 1 which is NaN. Instances created by new Animal have a count property initially, but Animal itself does not until you call increaseCount. this within a static method refers to the Animal class (constructor function) itself (if you call it via Animal.methodName(...)).

You could give Animal a count property:

Animal.count = 0;

Live Example:

class Animal {  constructor() {  }
static increaseCount() { this.count += 1; }
static getCount() { return this.count; }}Animal.count = 0;
Animal.increaseCount();console.log(Animal.getCount());Animal.increaseCount();console.log(Animal.getCount());

Define a const in class constructor (ES6)

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

Defining constants in es6 class for angular 1.5 controller

You aren't calling getActionConts inside of $onInit(). It works when you change this.getActionConsts.A to this.getActionConsts().A. Also you can use the class name instead of this.constructor its a bit cleaner. I used these docs if you want to read more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

When I work with constants I just use the const declaration and declare my constants outside of the class. Angular has some fancy ways of defining constants as well which I can't recall of the top of my head.

Access to a ES6 / ES7 static class variable within class and constructor

Static methods and properties are accessible through classes, not through this keyword:

class AddOrSelectAddress {    static allCountries = {        AD: "Andorra",        AE: "Vereinigte Arabische Emirate",        AF: "Afghanistan",        // ...    };
constructor() { console.log('new'); console.log(AddOrSelectAddress.allCountries); }}
const myInstance = new AddOrSelectAddress();

Pre ES6 Static Functions in a Class

How do I create static functions which can be called without an instance, and how do I assign static constants which can be accessed without an instance?

Both methods and constants are just properties of the class (constructor function) object, and are created by assignment:

var MyClassBase = function(str){
this.m_Data = str;
};
MyClassBase.STATIC_STRING = "Ooops";

See also JavaScript: Class.method vs. Class.prototype.method or Static variables in JavaScript.

When I create my class MyClass which inherits MyClassBase, then MyClass.STATIC_STRING is undefined. Is that normal class conventions?

Yes, this is normal in ES5 inheritance. To emulate ES6, you would need to manually set the prototype of the constructor:

Object.setPrototypeOf(MyClass, MyClassBase);

(or in ES5, one did use the now-deprecated __proto__).

Notice however that often enough you want to explicitly refer to MyBaseClass anyway.

how to define a static property in the ES6 classes

One way of doing it could be like this:

let _cards = [];
class Game{
static get cards() { return _cards; }
}

Then you can do:

Game.cards.push(1);
console.log(Game.cards);

You can find some useful points in this discussion about including static properties in es6.

Correctly declare static variables in JavaScript classes

Static class fields are a stage 3 proposal, meaning they're not yet an official part of the JavaScript language. (Stage 4 is the final stage.) You can read more about the proposal here and the proposal process here.

Currently, Chrome (as of version 72) is the only browser that supports static class fields.

To use this feature in other browsers you would need to use Babel with @babel/plugin-proposal-class-properties to transpile your code. If you're not already using Babel, however, this might be overkill.

Alternatively, you can assign a property to the class after initializing it. This isn't semantically identical, but works for your (and, indeed, most) use cases.

class AddOrSelectAddress {
// ...
}

AddOrSelectAddress.body = 'some initial value';

You can see this working in the below snippet.

class AddOrSelectAddress {  static changeBody(val) {    this.body = val;  }
static someMethod() { console.log('in someMethod body is', this.body); }
static someOtherMethod() { console.log('in someOtherMethod body is', this.body); }}AddOrSelectAddress.body = 'some initial value';
AddOrSelectAddress.someMethod();AddOrSelectAddress.changeBody('some other value');AddOrSelectAddress.someOtherMethod();


Related Topics



Leave a reply



Submit