2

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.

Rikard
  • 7,485
  • 11
  • 55
  • 92
  • Depends on how you want to access them. That implementation gives each instance a member named `type` but if you wanted statics more like how C# does them then you'd do something like `Person.type = 'person'`. Then it would only be attached to the class instead of the individual instances. – Mike Cluck Jan 25 '16 at 20:26
  • @MikeC there are many usecases for such properties, I didn't have a specific in mind. If we extend it [we can still use/change](http://www.es6fiddle.net/ijufl5c6/) that property. My question in more in lines like: _is this ok to do?_, or _is there a more correct way?_ that can be done from inside the Class. – Rikard Jan 25 '16 at 20:34
  • 3
    Then I'd say, yes, that's completely fine. [Although I wouldn't call those "static properties"](http://stackoverflow.com/a/1535687/371184). They're "instance properties" or just properties. – Mike Cluck Jan 25 '16 at 20:37

2 Answers2

10

You can create static getter:

"use strict";

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

console.log(Person.type) // 'person'
just-boris
  • 9,468
  • 5
  • 48
  • 84
3

As already said, what you are doing is creating an instance property. Adding such properties in the constructor is what the constructor is there for. This hasn't changed with ES6.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143