Reputation: 7805
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.
Upvotes: 2
Views: 4555
Reputation: 9746
You can create static getter:
"use strict";
class Person {
static get type() {
return 'person'
}
}
console.log(Person.type) // 'person'
Upvotes: 10
Reputation: 816312
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.
Upvotes: 3