1

I'm trying to learn a bit of 'advanced' Javascript, so I figured I'd make a simple typing game. Unfortunately, I've already gotten stuck early on, and I figure it's a stupid mistake where I am completely missing the point of something. Here's my code:

var TypingTest = new function() {

    this._playing = false;

    this.Play = function() {
        this._playing = true;
    }
    this.Stop = function() {
        this._playing = false;
    }

    $(document).keydown(function(e) {
        if(this._playing) {
                    // Reference point
            console.log(e);
        }
    });
}

The problem is, no matter what I instantiate the _playing variable to, the "reference point" is never reached. this._playing is always undefined, and I haven't the slightest clue why. Is it scope? Is it a protection thing? It beats me!

EDIT: I have jQuery imported and working. If I take out the if block, the game works fine.

Thank you!

4

1 に答える 1

4

問題は、イベントの範囲外であることです。イベントでthisは、オブジェクトではなくドキュメントを参照しています。オブジェクトへの参照をローカル変数にキャッシュすることで、これを修正できますthat

var TypingTest = new function() {
    ...
    var that = this;
    ...
    $(document).keydown(function(e) {
        if(that._playing) {
                    // Reference point
            console.log(e);
        }
    });
}
于 2013-05-16T02:24:26.883 に答える