将类中的HTMLElement成员的onclick属性设置为同一类的方法

Ash*_*and 1 javascript typescript

我试图在类实例中设置HTMLElement成员的onclick事件处理程序,但是我的两次尝试都有问题:

1:关键字不能使用

class ClassName {
  div: HTMLElement;
  constructor() {
    this.div = document.createElement('div');
    this.div.onclick = function(e) {
      this._onclick(); // keyword 'this' is not the instance in this scope
    }
  }
  _onclick() {
    alert('I've been clicked!');
  }
}
Run Code Online (Sandbox Code Playgroud)

2:错误:'无法将'void'转换为(ev:FocusEvent)=> any.

class ClassName {
  div: HTMLElement;
  constructor() {
    this.div = document.createElement('div');
    this.div.onclick =  this._onclick(); // error
  }
  _onclick() {
    alert('I've been clicked!');
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为这表明我对语言缺乏了解.如果有人可以请澄清并可能发布解决方案,将不胜感激!

bas*_*rat 5

使用特定于打字稿的箭头符号:

class ClassName {
  div: HTMLElement;
  constructor() {
    this.div = document.createElement('div');
    this.div.onclick = (e) => {
      this._onclick(); // keyword 'this' is the instance in this scope
    }
  }
  _onclick() {
    alert('I've been clicked!');
  }
}
Run Code Online (Sandbox Code Playgroud)

()=>而不是为你function()自动逃脱this,例如以下打字稿:

class ClassName {
    foo = "123"; 
    constructor(){
        var x = ()=>{
            alert(this.foo);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

生成以下javascript:

var ClassName = (function () {
    function ClassName() {
        var _this = this;
        this.foo = "123";
        var x = function () {
            alert(_this.foo);
        };
    }
    return ClassName;
})();
Run Code Online (Sandbox Code Playgroud)

通知var _this = this它保持this使用功能关闭内_this.foo