Reputation: 9249
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?
Upvotes: 2
Views: 5267
Reputation: 816414
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.
Upvotes: 3
Reputation: 78535
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);
}
}
Upvotes: 8