KyleM
KyleM

Reputation: 628

ES6 javascript Subclass not inheriting all variables?

So basically I have an es6 js class where constructor variables are created then assigned within a class method. Later I create a sub class that extends the first and pass all variables I wish to use to the subclass constructor and subsequently to the super method. After this one variable is correct and the other is undefined, both are created passed and logged in the same manner. Why would it be undefined??

class socket {
  constructor() {
    this.socket = {};
    this.base = '/*string*/';
    this.mainIndex;
    this.dashboard;
    this.user_id;
  }

  socket_start() {

    //do stuff here to start websocket

    self.socket.onmessage = function ( event ) {
      let stream = JSON.parse( event.data );
      this.mainIndex = stream.url.mainIndex; 
      this.dashboard = stream.url.dashboard; 
      this.user_id = stream.staffInfo.id; 
      this.base = stream.base;  

      console.log( this.user_id ); // "1"
      console.log( this.base); // "string"
    }
  }
}


class main extends socket {
  constructor( user_id, base, socket, mainIndex, dashboard ) {
  super( user_id, base, socket, mainIndex, dashboard );


  console.log( this.user_id ); // undefined   <--????
  console.log( this.base); // "string"
}

Upvotes: 0

Views: 255

Answers (1)

Hunter McMillen
Hunter McMillen

Reputation: 61512

Your parent class ignores any arguments that it is passed. Compare the two versions below:

class A {
  constructor() {
    this.name;
  }
}

class B extends A {
  constructor(name) {
    super(name)
  }
}

> new B("Hunter");
B {}

Now an example with the correct behavior:

class A {
  constructor(name) {
    this.name = name;
  }
}

class B extends A {
  constructor(name) {
    super(name)
  }
}

> new B("Hunter");
B { name: 'Hunter' }

Upvotes: 1

Related Questions