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!

Scott
  • 5,338
  • 5
  • 45
  • 70
  • Try `console.log(this);` and compare the result with what you expect. You're making wrong assumptions about what `this` refers to in your code – zerkms May 16 '13 at 02:24

1 Answers1

4

The problem is that you are out of scope in your event, this in your event is referring to the document not your object. You can fix this by caching the reference to your object in a local variable that:

var TypingTest = new function() {
    ...
    var that = this;
    ...
    $(document).keydown(function(e) {
        if(that._playing) {
                    // Reference point
            console.log(e);
        }
    });
}
Ibu
  • 42,752
  • 13
  • 76
  • 103