我应该在从另一个构造函数引用对象的属性时使用构造函数或实例吗?

时间:2017-07-17 15:11:22

标签: javascript oop object constructor

我正在写一个构造函数' " runGame"等方法" Game"的方法构造函数,如果我需要引用" GameBoard"的属性。构造函数应该使用构造函数的名称,如下所示:

function Game(){
   this.runGame(){
     var someProp = GameBoard.otherProp;
   }
}

或者我是否必须首先创建构造函数对象的实例,然后引用这样的实例。

var newGameBoard = new GameBoard();

function Game(){
   this.runGame(){
     var someProp = newGameBoard.otherProp;
   }
}

3 个答案:

答案 0 :(得分:1)

如果我以正确的方式理解您的问题,您需要的是组合,您需要在施工期间注入相关实例:

function Game(gameBoard) {
   this.gameBoard = gameBoard;
}

Game.prototype = {
    runGame: function() {
        // You access injected GameBoard through the 
        // own Game object's property "this.gameBoard"
        var someProperty = this.gameBoard.someProperty;
    }
};

var gameBoard = new GameBoard();
var game = new Game(gameBoard);

进一步阅读:

答案 1 :(得分:1)

如果每个游戏都有GameBoard,它应该是一个属性:

function Game(){
  this.board=new Board();
}

Game.prototype.runGame=function(){//real inheritance
  var someProp = this.board.otherProp;
};

答案 2 :(得分:0)

如果GameBoard(s)属于您逻辑中的Game,那么我就是这样做的

var Game = function(params) {
    this.options = params.options; // it could prove useful to instanciate a game using a set of rules
    this.gameBoards = params.gameBoards; // Already instanciated gameBoard(s)
    this.activeGameBoard = null; // if there are many gameboards it might be a good idea to keep track of the one that's currently active
    this.prop = '';
    // ... Initialize all the properties you need for your Game object
}

Game.prototype = {
    runGame: function(gameBoardIndex) {
        this.activeGameBoard = this.gameBoards[index];
        this.someProp = this.activeGameBoard.someProp;
    }
}

我知道我承担了很多事情,但我无法帮助它,它让我想起了我参与游戏和游戏板的唯一项目:p