【问题标题】:TypeScript: access outer "this" from a nested classic function, not breaking the linter "no-this-alias" ruleTypeScript:从嵌套的经典函数访问外部“this”,不违反 linter“no-this-alias”规则
【发布时间】:2021-05-31 10:14:37
【问题描述】:

我们在 TypeScript 项目中使用Airbnb's eslint config,它包括no-this-alias rule

这让我想知道如何在不违反此规则的情况下从嵌套的经典函数访问外部 this

代码如下:

class MyClass {
 
  name: string;

  target: EventTarget;
 
  constructor(name: string, target: EventTarget) {
    this.name = name;
    this.target = target;
  }
 
  initEventHandlers() {
    const self = this;
    function exampleEventHandler(this: EventTarget, e: Event) {
      console.log(this.somethingFromTheTarget);
      console.log(self.somethingFromMyClass);
    }
    this.target.addEventListener('exampleEvent', exampleEventHandler);
  }
}

从事件库调用事件处理函数,使用fn.call(this, e)this 设置为事件目标,在事件处理的范围内。显然,这里不适用箭头函数。

linter 的 const self = this; 行有问题。

我知道这是允许的:const { thisOneProperty } = this,然后可以在嵌套函数代码中使用thisOneProperty。但是当属性值更新时,这并没有好处。

这也可以:const myClass = { t: this };,然后我可以通过myClass.t 访问它。但这太丑了。

那么从事件处理函数中访问 MyClass 的this 的“干净”方式是什么?

【问题讨论】:

  • 这行不通有什么原因吗? tsplay.dev/kNreaw 使用箭头函数并从类的this.target 而不是函数的this 访问目标。
  • 我不确定我理解你的意思“事件处理函数是从事件库中调用的,使用 fn.call(this, e)”
  • 您可以在箭头函数中捕获访问外部对象的代码,并在处理程序中调用该箭头函数,但如果与外部对象有更多交互,这可能会变得很丑。
  • @LindaPaiste 我帖子中的代码已简化。在实际代码中,有许多目标并使用相同的处理函数。我提到fn.call(this, e) 只是为了表明通过将this 设置为发出事件的对象来调用事件处理函数。

标签: typescript typescript-eslint


【解决方案1】:

测试一下

class MyClass {
 
  name: string;

  target: EventTarget;
 
  constructor(name: string, target: EventTarget) {
    this.name = name;
    this.target = target;
  }
 
  initEventHandlers() {
    const self = {
      somethingFromMyClass: this.somethingFromMyClass.bind(this)
    };

    function exampleEventHandler(this: EventTarget, e: Event) {
      console.log(this.somethingFromTheTarget);
      console.log(self.somethingFromMyClass);
    }
    this.target.addEventListener('exampleEvent', exampleEventHandler);
  }
}

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 2020-11-27
    • 1970-01-01
    • 2017-01-12
    • 2015-12-18
    • 1970-01-01
    • 2013-08-15
    • 2019-08-20
    • 2011-02-13
    相关资源
    最近更新 更多