ES6 Class Property Definition

2019-09-12 09:37发布

问题:

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?

回答1:

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";.