0

在下面的代码中,我this.listercreate_components方法中得到了未定义的引用。我试图理解this(显然根据您调用该方法的方式而变化)的含义,但如果有人能指出为什么this不绑定到的规则ScreenCreator以及我如何实现这一点,那就太好了。

谢谢!

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

4

2 回答 2

2

在外部创建一个变量(我通常称之为它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));  
}
于 2022-01-28T19:24:40.183 回答
1

你可以this in a variable像这样存储

ScreenCreator.prototype.create_components = function() {
  let screenCreatorThis = this
  this.goldenlayout.registerComponent('comp1', function (container, state) {    
    screenCreatorThis.lister.init(container, state);
  });  
}
于 2022-01-28T19:24:55.627 回答