javascript - JavaScript 中公共(public)字段声明的意义是什么?

标签 javascript node.js

所以,根据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.

起初我认为,如果我使用上面的构造函数创建一个对象并且不传递 heightwidth 参数,我会得到 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/

相关文章:

javascript - TypeScript 为 HTMLCollectionOf<Element>、NodeCollection<Element>、google 自动完成表单设置 css 样式

javascript - trim 前导和尾随空格

javascript - 如何设置html表格高度和列宽?

node.js - npm install 卡在提取 : zone. js

javascript - r.js 可以解决使用 npm 安装的依赖项吗?

javascript - 找出所有可能的组合

javascript - JavaScript数组计算和转换

javascript - Firebase 函数用于获取 ajax post 并 console.log 它

node.js - 为 Heroku 上的 Mongo Labs 数据库配置 Node.js 连接字符串

node.js - 使用 Handlebars.js 显示 JSON 数组