代码之家  ›  专栏  ›  技术社区  ›  Noob

JavaScript中公共字段声明的意义是什么?

  •  1
  • Noob  · 技术社区  · 5 年前

    那么根据 MDN 文件:

    class Rectangle {
      height = 0;
      width;
      constructor(height, width) {
        this.height = height;
        this.width = width;
      }
    }
    

    通过预先声明字段,类定义变得更加简单 自我记录,并且字段始终存在。

    如上所述,可以使用默认值或不使用默认值声明字段 价值

    起初我认为,如果我使用上面的构造函数创建一个对象,并且不通过 身高 和 宽度 我会的 height = 0 . 然而,事实并非如此。它是 undefined .

    let rectangle = new Rectangle()
    
    console.log(rectangle.height) // this is undefined
    

    所以,现在我无法理解公共字段声明的意义。它们看起来像多余的代码行,没有太多的用途。它们带来了什么好处?谢谢你的解释。

    2 回复  |  直到 5 年前
        1
  •  2
  •   CertainPerformance    5 年前

    您正在分配给 height 在构造函数中,有效覆盖类字段赋值:

    this.height = height;
    

    类字段在构造函数主体运行之前为实例分配属性,在大多数情况下,您的原始代码几乎等同于

    class Rectangle {
      constructor(height, width) {
        this.height = 0;
        this.width;
        this.height = height;
        this.width = width;
      }
    }
    let rectangle = new Rectangle()
    
    console.log(rectangle.height)

    它们看起来像多余的代码行,没有太多的用途。

    是的,如果您在构造函数中无条件地分配这些属性,那么拥有这些字段并没有多大帮助——它会告诉代码的读者 将存在哪些实例属性,但这也意味着需要额外的代码。

    当您想要分配实例属性时,类字段更有用 不要 立即被覆盖,例如:

    class Rectangle {
      height = 5;
      constructor(width) {
        this.width = width;
      }
    }
    let rectangle = new Rectangle(8)
    
    console.log(rectangle.height, rectangle.width)

        2
  •  1
  •   Barmar    5 年前

    线路 this.height = height; 将声明中的默认值替换为 height 参数没有提供任何参数没有区别,它仍然执行赋值。当未提供参数时,参数默认为 undefined .

    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;
      }
    }
    
    推荐文章