Callum Linington
Callum Linington

Reputation: 14417

ES6 Class Property Definition

So I've read around stackoverflow. In ES6 this is invalid:

class MyClass {
   myProperty = "";

   constructor() {
       this.myProperty = "Hey";
   }
}

But it is valid in ES7.

However, is this valid:

class MyClass {
    setViewModel(viewModel) {
        this.internalViewModel = viewModel;
    }

    get viewModel() { return this.internalViewModel }
}

Here I haven't defined internalViewModel until I've actually set it. I expect that if you haven't called myClass.setViewModel(something) before you call myClass.viewModel, you will get undefined returned from myClass.viewModel.

Is this correct?

If you have this ES7 class and you tried to access myProperty like so myClass.myProperty would you get the expected "Hey" or not?

Upvotes: 2

Views: 958

Answers (1)

Bergi
Bergi

Reputation: 664538

Is this ES6 correct?

Yes.

Although it might be considered a bad practise not to create all properties in the constructor.

If you have this ES7 class and you tried to access myProperty like so myClass.myProperty would you get the expected "Hey" or not?

Yes, but notice that myProperty is not a class but an instance property.

var myClass = new MyClass;
myClass.myProperty; // "Hey"

Also, the instance field declaration with the initialiser is totally superfluous anyway, because it's overwritten right away through the near-equivalent this.myProperty = "Hey";.

Upvotes: 2

Related Questions