ES6 Class Property Definition

陌路散爱 提交于 2019-12-11 23:27:52

问题


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



来源:https://stackoverflow.com/questions/35468538/es6-class-property-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!