Typescript 私有方法 "is not a function"

Typescript private method "is not a function"

我可能误解了一些概念,但在阅读了关于 Whosebug 的 4 个主题和 "private members in typescript" 的文档之后 - 我仍然感到困惑。

我正在编写简单的鼠标 IO(第一个打字稿项目)。这是鼠标故障的完整代码 class:

class Mouse {
    public left: MouseKeyData = new MouseKeyData();
    public right: MouseKeyData = new MouseKeyData();
    public whell: MouseKeyData = new MouseKeyData();

    public x: number = 0;
    public y: number = 0;

    private crossBrowserButton(e: any):string {
        switch (e.button) {
            case 0: return 'left';
            case 1: return 'whell';
            case 2: return 'right';
            case 3: return 'back';
            case 4: return 'forward';
        }
        return 'none';
    }


    private onMouseDown(e: any):void {
        let target: MouseKeyData = this.left;
        try {console.log(this.crossBrowserButton(e))} catch (a) {console.warn(a)} finally {}
        if(target) {
            target.press();
        }
    }

    private onMouseUp(e: any):void {
        let target: MouseKeyData = this.left;
        if(target) {
            target.release();
        }
    }

    private onMouseMove(e: any): void {
        this.x = e.pageX;
        this.y = e.pageY;
    }

    public constructor() {
        let anchor = document.body;

        anchor.addEventListener('mousedown', this.onMouseDown);
        anchor.addEventListener('mouseup', this.onMouseUp);
        anchor.addEventListener('mousemove', this.onMouseMove);

    }
}

我曾经在onMouseDownonMouseUp中调用this.crossBrowserButton(e),但我只得到了this.crossBrowserButton is not a function(…)

我想我在某个地方丢失了 this 范围,但是 this.left 工作得很好。

提前致谢!

好的,我想通了:我在事件中将 this 绑定到 document.body,然后 - 我在方法中使用了这个 this

感谢评论。各位晚安!

听起来你做了与你应该做的完全相反的事情。在您的原始代码中,事件侦听器的执行范围存在问题。它们不受 class 范围的限制,因此将在它们来自 运行 的上下文中执行。

您的事件绑定应如下所示。

    anchor.addEventListener('mousedown', this.onMouseDown.bind(this));
    anchor.addEventListener('mouseup', this.onMouseUp.bind(this));
    anchor.addEventListener('mousemove', this.onMouseMove.bind(this));