samedi 8 septembre 2018

Weird behaviour when trying to do prototype inheritance

I am trying to do prototype inheritance in combination with the State Design Pattern so create a user interface that is easy to maintain.

All the user interface states inherit from a parent state called State. Whenever a state changes from one to another the user interface updates. (I am using knockoutJS's two way binding to help achieve this)

The state pattern requires that I keep a reference to the context in which the states are used. In this case I keep a reference to the _context so I can access the socket which socketIO creates upon connection.

The issue is that my _context reference seems to get lost and I cannot execute the emit function on the socket because of this. My background is Java,PHP and C,so I am still struggling to comprehend how inheritance works in Javascript.

Below is the code from one of the states. It is the YouAreConnected state. What I want it to do is emit "createRoom" on the socket, however I can't do this because it says _context is undefined.

define(['voice/states-new/State'],
function(State){

  var YouAreConnected = function YouAreConnected(context){

    if(!context){
        throw Error('context must be set.');
    }
    else{
        this.__proto__._context = context;
    }

    this.init = function(){
      console.log(this.__proto__);    
      console.log(this.constructor.prototype);

    //////  THIS IS THE CODE I NEED TO WORK.  
    this.__proto__._context.socket.emit('createRoom',_context.userId);

    }
  }

  var state = new State();

  // I ALSO TRIED ADDING _context to the prototype here.

  YouAreConnected.prototype = Object.create(state);
  var p = YouAreConnected.prototype;
  p.constructor = YouAreConnected;
  p.isStatusLightVisible = false;
  p.isSpinnerVisible = false;



  return YouAreConnected;

});

I tried setting _context outside the scope of the constructor,then adding it to the prototype of the State,I tried many combinations or things and cannout seem to get _context to stick. In the chrome inspector I also noticed what looks like a recursive "overflow" of inheritance. A screen shot of this is below. I must be doing something wrong,but I am not sure what.

enter image description here

Aucun commentaire:

Enregistrer un commentaire