我想学一点“高级”的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块,游戏就能正常运行。
谢谢!
发布于 2013-05-16 10:24:27
问题是您的事件超出了范围,事件中的this引用的是文档而不是对象。可以通过在局部变量that中缓存对对象的引用来修复此问题
var TypingTest = new function() {
    ...
    var that = this;
    ...
    $(document).keydown(function(e) {
        if(that._playing) {
                    // Reference point
            console.log(e);
        }
    });
}https://stackoverflow.com/questions/16578001
复制相似问题