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

时间:2013-07-09 21:11:35

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

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

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

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

2 个答案:

答案 0 :(得分: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!');
  }
}

()=>代替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

中的闭包来维护_this.foo

答案 1 :(得分:3)

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