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

Set the onclick property of a HTMLElement member in a class to a method of the same class

本文关键字:方法 一类 属性 HTMLElement 成员 onclick 设置      更新时间:2023-09-26

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

1:关键字this不能使用

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

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

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

使用特定于typescript的箭头表示法:

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

()=>而不是function()会自动为您转义this,例如以下类型脚本:

class ClassName {
    foo = "123"; 
    constructor(){
        var x = ()=>{
            alert(this.foo);
        }
    }
}

生成以下javascript:

var ClassName = (function () {
    function ClassName() {
        var _this = this;
        this.foo = "123";
        var x = function () {
            alert(_this.foo);
        };
    }
    return ClassName;
})();

注意var _this = this,它使用函数_this.foo 内的闭包来维护this

this关键字绑定到调用函数的上下文。当函数作为DOM元素(如onclick)的事件的结果被调用时,它指向该元素。

第一个例子的一个变通方法是将构造函数上下文保留在一个新变量中,该变量将调用that:

class ClassName {
  div: HTMLElement;
  constructor() {
    this.div = document.createElement('div');
    var that = this;   //that and this both point to the new Object
    this.div.onclick = function(e) {
                       //this now points elsewhere
      that._onclick(); //that still point to the new object
    }
  }
  _onclick() {
    alert('I''ve been clicked!');
  }
}

在第二个示例中,通过添加括号来计算onclick函数,因此将其结果分配给div.onclick属性。

正确的代码是:

class ClassName {
  div: HTMLElement;
  constructor() {
    this.div = document.createElement('div');
    this.div.onclick =  this._onclick;
  }
  _onclick() {
    alert('I''ve been clicked!');
  }
}