繁体   English   中英

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

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

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

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

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调用之后分配,如果存在的话 - 并且必须在构造函数中引用this之前完成super调用也):

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM