如何在嵌套回调中引用正确的 'this'

How to refer to correct 'this' in nested callback

在下面的代码中,我在 create_components 方法中获得了 this.lister 的未定义引用。我试图理解 this 的含义(显然会根据您调用该方法的方式而变化)但是如果有人能指出 this 不绑定到 [=16 的规则,那就太好了=] 我怎样才能做到这一点。

谢谢!

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

在外部创建一个变量(我通常称之为 self,但任何东西都可以)并在内部使用它。

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

或者,您可以使用箭头函数,因为它们不会创建自己的 this 上下文。

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

如果你想要一种奇怪的方式来做到这一点,你可能不应该使用这种方式,除非其他方式不起作用,那就是:(在函数之后添加 .bind(this)

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

你可以像

一样存储this in a variable
ScreenCreator.prototype.create_components = function() {
  let screenCreatorThis = this
  this.goldenlayout.registerComponent('comp1', function (container, state) {    
    screenCreatorThis.lister.init(container, state);
  });  
}