简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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