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

问题描述 投票:0回答:1

我试图使用一个基本计算来设置一个字段值,这个计算使用了我的构造函数中设置的值,但是由于某些原因,当我引用我的构造函数中初始化的一些值时,我得到了TypeError。Cannot read property of undefined.

虽然当我引用 this 在没有尝试访问任何在我的构造函数中设置的值(margin或dimension)的情况下,我没有得到这个错误,并且可以看到初始化的对象。

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)

javascript es6-class
1个回答
4
投票

类字段,去糖化,总是在附近运行。开始 的构造函数,在属性被分配给 this (虽然类字段是在 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 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);
© www.soinside.com 2019 - 2024. All rights reserved.