Home > Software design >  When are JS object variables assigned a value?
When are JS object variables assigned a value?

Time:12-21

I'm just a little confused as to when Object variables are assigned a value.

As far as I remember (and this is from long-lost and hazy Java knowledge so may not be relevant), object variables are initialised prior to constructor calls. I had thought that explicitly declared values would be too, but that doesn't seem to be the case.

For example:

I've a parent class, Shape:

class Shape {
  constructor(data) {
    this._data = data;
    this._data.markup = this._generateMarkup();
  }
}

and a child, Circle:

class Circle extends Shape {
  _elementName = 'test';
  
  constructor(data) {
    super(data);
    console.log({data});
  }
  
  _generateMarkup() {
     console.log(this._elementName);
    return `<div >Test</div>`
  }
}

this._elementName is returning undefined.

This could well be a mistake on my part, but why is _generateMarkup() - essentially a property of the child - accessible in the parent constructor, but _elementName is not?

codepen link

class Shape {
  constructor(data) {
    this._data = data;
    this._data.markup = this._generateMarkup();
  }
}

class Circle extends Shape {
  _elementName = 'test';
  
  constructor(data) {
    super(data);
    console.log({data});
  }
  
  _generateMarkup() {
     console.log(this._elementName);
    return `<div >Test</div>`
  }
}

new Circle({});

Thanks

CodePudding user response:

AFAIK the properties of a class are added and initialized in the constructor. The _generateMarkup is not a property per se, it's a method on the class; it's defined before the constructor is called.

In this case if you want the _elementName to be defined and have a value, you need to add it to the constructor code:

constructor() {
  ...
  this._elementName = 'test';
  ...
}

On a sidenote, it's generally a bad practice to call methods which aren't inherited or defined on the class.

  • Related