[英]Why does my class field appear as undefined when referencing a value set in the constructor
I am trying to set a field value using a basic calculation that uses values set in my constructor, though for some reason when i reference some of the values initialised in my constructor, i get TypeError: Cannot read property of undefined.我正在尝试使用使用构造函数中设置的值的基本计算来设置字段值,但由于某种原因,当我引用构造函数中初始化的某些值时,我得到 TypeError:无法读取未定义的属性。
Though when i reference this
without trying to access any of the values set in my constructor (margin or dimension), i do not get this error and can see the initialised object.虽然当我引用
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 fields, de-sugared, always run near the beginning of the constructor, before properties are assigned to this
(though class fields are assigned after a super
call, if present - and a super
call must be done before references to this
in the constructor too): 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)
You can't use a class field if you want to reference properties created in the constructor.如果要引用在构造函数中创建的属性,则不能使用 class 字段。 You'll have to put that functionality into the constructor instead.
您必须将该功能放入构造函数中。
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.