如何访问事件侦听器内的类函数

Lan*_*box 1 javascript prototype addeventlistener

我在这里遇到一个小问题,我不想向单击事件添加事件侦听器。当点击发生时,函数会正常触发,但是当它应该调用另一个函数时,它会给出错误:

TypeError: this.addEvent is not a function
Run Code Online (Sandbox Code Playgroud)

代码:

class TEST {
    construct(){
        this.events = [];
    }
}

TEST.prototype.ready = function(callback) {
    if (document.readyState!='loading') callback();
    else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
    else document.attachEvent('onreadystatechange', function(){
        if (document.readyState=='complete') callback();
    });
}

TEST.prototype.addEvent = function (event) {
    this.events.push(event);
}

TEST.prototype.clickEvent = function (e) {
    var pos = {
        x: e.pageX,
        y: e.pageY
    };

    var event = {
        type: 'click',
        data: pos,
        timestamp: new Date()
    };

    this.addEvent(event);
}

TEST.prototype.init = function () {
    document.addEventListener('click', this.clickEvent);
}

var test = new TEST();
test.ready(function(){
    test.init();
});
Run Code Online (Sandbox Code Playgroud)

JSFiddle: https:
//jsfiddle.net/x2hLw009/

任何帮助表示赞赏,谢谢!

编辑

我添加了绑定到 addEventListener:

document.addEventListener('click', this.clickEvent.bind(this));
Run Code Online (Sandbox Code Playgroud)

但是当函数继续到 this.addEvent() 时,我收到新错误:

TypeError: this.events is undefined
Run Code Online (Sandbox Code Playgroud)

在这一行:

this.events.push(event);
Run Code Online (Sandbox Code Playgroud)

小智 5

它崩溃的原因是this范围界定。函数内部的“this”clickEvent与调用它的内容相关。

因此,由于文档正在调用它,因此“this”可能会指代该文档。如果你想强制它引用当前对象,你将使用绑定原型。

document.addEventListener('click', this.clickEvent.bind(this));