【问题标题】:Accessing a value from different instances从不同实例访问值
【发布时间】:2011-12-19 21:02:56
【问题描述】:

我正在创建一个应该可以同时运行多个游戏的记忆游戏。如果您重新启动游戏或运行新游戏,应该可以存储最好的分数(最高分)。

现在解决问题。如果我将变量“bestScore”存储为“this.bestScore”,它将指向特定游戏,这意味着当我重新启动游戏时它将被重置。我已经尝试使用“var”,但是当我尝试使用“DESKTOP.MemoryApp.bestScore”(参见下面的代码)访问它时,它是未定义的。

那么,存储这个值以便在所有游戏中都可以访问的最佳方式是什么?

DESKTOP.MemoryApp = function(){

this.score = 0;
this.bestScore = 0;
var bestScore = 0;

}

DESKTOP.MemoryApp.prototype.wonGame = function(){

// code...

console.log(this.bestScore) // <-- points to a specific game
console.log(DESKTOP.MemoryApp.bestScore // <-- undefined
console.log(bestScore) <-- bestScore is not defined

}

【问题讨论】:

    标签: javascript variables object


    【解决方案1】:

    在第二种情况下尝试访问它时存储它:

    // this will work from the "constructor" function as well
    DESKTOP.MemoryApp.bestScore = 100;
    console.log(DESKTOP.MemoryApp.bestScore); // of course, 100
    

    【讨论】:

      猜你喜欢
      • 2013-05-08
      • 2017-03-04
      • 2016-03-23
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多