如何在类的实例中声明类的实例?

时间:2016-03-14 10:10:04

标签: javascript class

我正在做一个简单的hmtl / js游戏。我想在DataofGame中获取游戏的所有数据。它就像网球,比网球简单:只有套装和比赛。在changeinSet上调用click

但我认为私有变量存在问题,所以它不起作用。 Uncaught TypeError: Cannot read property 'WordsoftheGame' of undefined

    //Added
    document.getElementById('playboutton').addEventListener('click', newGame);

    function newGame() {
        var DataofGame = new newGameData();
    }

    // New game
    function newGameData() {

        this.pointTeam1 = 0;
        this.pointTeam2 = 0;
        this.WordsoftheGame = ShuffleListe();
        this.ASet = new aSet();
    }

    //How the set is manage ********************

    function aSet() {
        var oneWord = DataofGame.ListeMot;
        // display the word and delete it from the list
        document.getElementById('jouer').innerHTML = oneWord[0];
        DataofGame.WordsoftheGame.shift();
        this.turn = true;
        this.score = 0;
    }

    function changeinSet() {
        DataofGame.ASet.score += 1;
        //This is the other team's turn:
        DataofGame.ASet.turn = !DataofGame.ASet.turn;

    };

    //shuffle liste
    ListOfWords = ['Artiste', 'Appeler', 'Cheval', 'Choisir', 'Ciel', 'Croire', 'Dormir'];

    function ShuffleListe() {
        data = shuffle(ListOfWords);
        return data;
    }

2 个答案:

答案 0 :(得分:1)

function newGameData(){

  this.pointTeam1=0;
  this.pointTeam2=0;
  this.WordsoftheGame= ShuffleListe();
  this.ASet=new aSet();
}

//How the set is manage ********************

function aSet(){
  var oneWord=DataofGame.ListeMot;
  // display the word and delete it from the list
  document.getElementById('jouer').innerHTML=oneWord[0];
  DataofGame.WordsoftheGame.shift(); // << DataofGame not assigned yet
  this.turn=true;
  this.score=0;
}

当您访问DataofGame时,它尚未分配,因为您在调用aSet()时位于构造函数内部。

你想要实现的目标并不完全清楚,但如果它为你的对象添加一个ASet方法,你可以这样写:

function newGameData(){

  this.pointTeam1=0;
  this.pointTeam2=0;
  this.WordsoftheGame= ShuffleListe();
  this.ASet = function() {
        // your code
  };
}

注意你的名字编码风格有点乱,你应该一直使用大写字母。用法是用大写字母开始构造函数名称,其余用小写字母。

答案 1 :(得分:0)

您可以让函数返回包含数据的对象,或者只是设置对象。

function newGameData(){
    return { 
          pointTeam1 : 0,
          pointTeam2 : 0,
          WordsoftheGame : ShuffleListe(),
          ASet : new aSet() 
  }
}

但我建议在javascript中搜索如何使用对象。也许这会有所帮助:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

相关问题