[英]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.