Tiago Almeida
Tiago Almeida

Reputation: 13

Javascript Class Variables Access

question here. I have this code

class Primary {
   constructor() {
      const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(this));
      console.log(methods);
   }
}
class Secondary extends Primary {
   myVar = '';
   test() {
      //Do Nothing
   }
}

And if I initiate the Secondary class it will print ['constructor', 'test'], but I cant do the same to the variables in the secondary class. Does anyone else know how or if this is possible?

Upvotes: 1

Views: 39

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

Class field declarations are only syntax sugar for assigning properties to the instance in the constructor:

class Secondary extends Primary {
   myVar = '';

is

class Secondary extends Primary {
  constructor() {
    super();
    this.myVar = '';
  }

The property is on the instance, not on the prototype - and the super call occurs before the the property is assigned (there's no way to change that; super calls are required before the instance can be accessed in the constructor).

I'd add a different method to the superclass that examines the variables needed, that can be called after an instance has been fully initialized:

class Primary {
  checkProps() {
    const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(this));
    const instanceProps = Object.getOwnPropertyNames(this);
    console.log(methods);
    console.log(instanceProps);
  }
}
class Secondary extends Primary {
  myVar = '';
  test() {
    //Do Nothing
  }
}

const s = new Secondary();
s.checkProps();

Upvotes: 4

Related Questions