所以,根据MDN文档:
class Rectangle {
height = 0;
width;
constructor(height, width) {
this.height = height;
this.width = width;
}
}
By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.
As seen above, the fields can be declared with or without a default value.
起初我认为,如果我使用上面的构造函数创建一个对象并且不传递 height 和 width 参数,我会得到 height = 0
。然而,这并不是个例。它是未定义
。
let rectangle = new Rectangle()
console.log(rectangle.height) // this is undefined
所以,现在我无法理解公共(public)字段声明的意义。它们看起来像是多余的代码,没有太多目的。它们带来什么好处?感谢您的任何解释。
最佳答案
行 this.height = height;
将声明中的默认值替换为 height
参数的值。不提供参数没有什么区别,它仍然执行赋值。当未提供参数时,该参数默认为未定义
。
您可以检查这一点而不覆盖初始默认值:
class Rectangle {
height = 0;
width;
constructor(height, width) {
if (height !== undefined) {
this.height = height;
}
this.width = width;
}
}
或者您可以在构造函数参数列表中提供默认值,而不是属性声明。
class Rectangle {
height;
width;
constructor(height = 0, width = 0) {
this.height = height;
this.width = width;
}
}
关于javascript - JavaScript 中公共(public)字段声明的意义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69982784/