问题描述
所以我已经阅读了stackoverflow。在ES6中,这是无效的:
class MyClass {
myProperty =;
构造函数(){
this.myProperty =嘿;
}
}
但它在ES7中有效。
但是,这是有效的:
class MyClass {
setViewModel viewModel){
this.internalViewModel = viewModel;
}
获取viewModel(){return this.internalViewModel}
}
这里我没有定义 internalViewModel
,直到我实际设置它。我希望如果您在调用 myClass.viewModel
之前未调用 myClass.setViewModel(something)
从 myClass.viewModel
返回未定义
。
是这是正确的吗?
如果你有这个ES7类,你试图访问 myProperty
像这样 myClass.myProperty
你会得到预期的Hey
还是不?
>
虽然这可能被认为是在构造函数中不创建所有属性的坏习惯。
是的,但注意 myProperty
不是一个类,而是一个insta nce财产。
var myClass = new MyClass;
myClass.myProperty; //Hey
此外,与初始化器的实例字段声明完全是多余的,因为它是通过近似等价的 this.myProperty =Hey;
。
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?
Yes.
Although it might be considered a bad practise not to create all properties in the constructor.
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";
.
这篇关于ES6类属性定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!