Search code examples
javascriptthisgolden-layout

How to refer to correct 'this' in nested callback


In the following code, I get undefined reference for this.lister in the create_components method. I am trying to understand the meaning of this (apparently changes based on how you call the method) but it would be great if someone can point out the rule why this does not bind to the ScreenCreator and how can I achieve that.

Thank you!

function ScreenCreator(config, container) {
  this.lister = new Lister();
  this.goldenlayout = new GoldenLayout(config, container);
  this.create_components();
  this.goldenlayout.init();
}

ScreenCreator.prototype.create_components = function() {
  this.goldenlayout.registerComponent('comp1', function (container, state) {    
    this.lister.init(container, state);
  });  
}


Solution

  • Create a variable in the outer portion (I usually call it self, but anything works) and use that inside.

    function ScreenCreator(config, container) {
      this.lister = new Lister();
      this.goldenlayout = new GoldenLayout(config, container);
      this.create_components();
      this.goldenlayout.init();
    }
    
    ScreenCreator.prototype.create_components = function() {
      const self = this;
      this.goldenlayout.registerComponent('comp1', function (container, state) {    
        self.lister.init(container, state);
      });  
    }
    

    Alternatively, you can use an arrow function, since they don't create their own this context.

    ScreenCreator.prototype.create_components = function() {
      this.goldenlayout.registerComponent('comp1', (container, state) => {    
        this.lister.init(container, state);
      });  
    }
    

    If you want a weird way to do it, which you probably shouln't use unless the others aren't working, here's that: (adding .bind(this) after function)

    ScreenCreator.prototype.create_components = function() {
      this.goldenlayout.registerComponent('comp1', (function (container, state) {    
        this.lister.init(container, state);
      }).bind(this));  
    }