Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);
  });  
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));  
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading