为什么我的 class 字段在引用构造函数中设置的值时显示为未定义

Why does my class field appear as undefined when referencing a value set in the constructor

我正在尝试使用使用构造函数中设置的值的基本计算来设置字段值,但出于某种原因,当我引用构造函数中初始化的某些值时,我得到 TypeError: Cannot read 属性 的未定义。

虽然当我引用 this 而不尝试访问我的构造函数中设置的任何值(边距或维度)时,我没有收到此错误并且可以看到初始化的对象。

class viz {
  constructor(dimension, margin) {
    this.dimension = dimension;
    this.margin = margin;
  }

  width = this.dimension.width - this.margin.left - this.margin.right;
  height = this.dimension.height - this.margin.top - this.margin.bottom;
}

const margin = { left: 40, right: 40, top: 40, bottom: 20 };
const dimension = { width: 1000, height: 600 };
let visual = new viz(dimension,margin)

Class 字段,去糖,总是 运行 在构造函数的 开始 附近,在属性分配给 this 之前(尽管 class 字段是在 super 调用之后分配的,如果存在 - 并且 super 调用也必须在构造函数中对 this 的引用之前完成):

class Parent {
}
class viz extends Parent {
  constructor(dimension, margin) {
    console.log('before super in constructor');
    super();
    console.log('after super');
    this.dimension = dimension;
    this.margin = margin;
  }

  something = console.log('class field');
  width = this.dimension.width - this.margin.left - this.margin.right;
  height = this.dimension.height - this.margin.top - this.margin.bottom;
}

const margin = { left: 40, right: 40, top: 40, bottom: 20 };
const dimension = { width: 1000, height: 600 };
let visual = new viz(dimension,margin)

如果要引用在构造函数中创建的属性,则不能使用 class 字段。您必须将该功能放入构造函数中。

class viz {
  constructor(dimension, margin) {
    this.dimension = dimension;
    this.margin = margin;
    
    
    this.width = this.dimension.width - this.margin.left - this.margin.right;
    this.height = this.dimension.height - this.margin.top - this.margin.bottom;
  }
}

const margin = { left: 40, right: 40, top: 40, bottom: 20 };
const dimension = { width: 1000, height: 600 };
let visual = new viz(dimension,margin)

console.log(visual);