0

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

Validus Oculus
  • 2,756
  • 1
  • 25
  • 34

2 Answers2

2

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));  
}
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • I had tried `self` method before posting but I think browser cached my page because it was not working. I tried again it works. I cannot use the arrow function, golden layout is complaining about it. Did not dig in on that yet, but I will check it. – Validus Oculus Jan 28 '22 at 19:30
1

You could store this in a variable like

ScreenCreator.prototype.create_components = function() {
  let screenCreatorThis = this
  this.goldenlayout.registerComponent('comp1', function (container, state) {    
    screenCreatorThis.lister.init(container, state);
  });  
}
Kureteiyu
  • 529
  • 4
  • 10