Typescript私有方法“不是函数”

时间:2016-10-02 00:31:43

标签: javascript typescript private

我可能错过了一些概念,但在阅读了有关stackoverflow的4个主题以及“打字稿中的私人成员”的文档后 - 我仍然感到困惑。

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

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);

    }
}

我曾经在this.crossBrowserButton(e)onMouseDown内拨打onMouseUp,但我只获得this.crossBrowserButton is not a function(…)

我认为我遗失了this范围,但this.left完美无缺。

提前致谢!

2 个答案:

答案 0 :(得分:1)

听起来你做的与你应该做的完全相反。在原始代码中,事件侦听器的执行范围存在问题。它们不受类的范围约束,因此将在它们运行的​​上下文中执行。

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

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

答案 1 :(得分:0)

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

感谢您的评论。晚安伙计们!