Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class static properties

In the new ES6 Class syntax it is not possible to do

class Person {
    this.type = 'person';

But if I define the property inside the contructor it works:

class Person {
    constructor(name) { //class constructor
        this.name = name;
        this.type = 'person';
    }

I know the possibility to have properties outside methods is being discussed but as of today and what relates to the ES6 specs it is not possible.

Is my solution a correct way to define static properties for the Class (for semantic reasons I defined those properties inside the constructor but it seems to work inside other methods)? Is there a better way?

I was looking at the spec in Method Defenition and found no information about this.

like image 795
Rikard Avatar asked Apr 16 '26 15:04

Rikard


1 Answers

You can create static getter:

"use strict";

class Person {
  static get type() {
    return 'person'
  }
}

console.log(Person.type) // 'person'
like image 112
just-boris Avatar answered Apr 19 '26 05:04

just-boris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!