将类中HTMLElement成员的onclick属性设置为同一类的方法
Set the onclick property of a HTMLElement member in a class to a method of the same class
我试图在类实例中设置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!');
}
}
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 数组在递归方法中设置为null
- 打破承诺链的好方法是什么
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 使用“;这个“;JavaScript原型方法中的关键字
- 序列化数据属性中对象的最可靠方法
- 使用Objective-C的JavaScript注入方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 有没有一种方法可以防止img get请求使用css或js发生
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 有没有更花哨的方法可以在同一类中获得上一个项目
- ES6 从同一类中调用类方法
- 从同一类中的另一个方法调用 java 脚本类内的方法
- 从同一类中的另一个方法调用 javascript 类方法
- 为什么我不能从同一类中的另一个方法调用此方法
- 将类中HTMLElement成员的onclick属性设置为同一类的方法
- 传递$的结果.将getJSON转换为同一类的另一个方法
- 在同一类的另一个方法中调用一个方法
- Javascript OOP -从同一类的不同方法调用方法