can es6 class have public properties as well as functions?

5.2k views Asked by At

All the examples of classes I see are

class myClass{
    constructor(){}
    someFunction(){}

what I want to add is

    someObject {myvalue:value}
}

this doesn't seem to compile. An old fashioned object would be

{
    somefunction: function(){}
    someProperty:  {myvalue:value}
} 

is this not possible in es6 classes?

2

There are 2 answers

4
CodingIntrigue On BEST ANSWER

You'd need to put it inside your constructor:

class myClass{
    constructor(){
        this.someObject = { myvalue:value };
    }
}
var obj = new myClass();
console.log(obj.someObject.myvalue); // value

If required, you can add the object onto the prototype chain the same as you would in ES5:

class myClass{
    constructor(){

    }
}
myClass.prototype.someObject = { myvalue:value };
var obj = new myClass();
console.log(obj.someObject.myvalue); // value

Note that there is no such thing as real private properties on a class. Any variable you attach to a class is public.

There is a Stage 0 proposal for Class Properties in ES7. If using Babel, this can be enabled using Experimental mode, allowing the following:

class MyClass {
  myProp = {value: "one"};
  constructor() {
    console.log(this.myProp);
  }
}
2
Felix Kling On

There is an easy way to simulate properties: getters.

var obj = {myvalue:value};

class Foo {
    get someProperty() {
       return obj;
    }
}

Whether it makes sense to use it entirely depends on the use case.