Javascript单例函数不工作

Javascript singleton function not working

本文关键字:工作 函数 单例 Javascript      更新时间:2023-09-26

我正试图学习一点"高级"Javascript,所以我想我会做一个简单的打字游戏。不幸的是,我一开始就被困住了,我认为这是一个愚蠢的错误,我完全错过了一些事情的重点。下面是我的代码:

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

问题是,无论我将_playing变量实例化为什么,都不会到达"参考点"。this._playing总是undefined,我一点也不知道为什么。是范围吗?这是一种保护吗?这难倒我了!

编辑:我有jQuery导入和工作。如果我拿出if块,游戏工作正常。

谢谢!

问题是您超出了事件的范围,事件中的this指的是文档而不是您的对象。您可以通过在本地变量that中缓存对对象的引用来修复此问题:

var TypingTest = new function() {
    ...
    var that = this;
    ...
    $(document).keydown(function(e) {
        if(that._playing) {
                    // Reference point
            console.log(e);
        }
    });
}