2017-07-17 95 views
-2

虽然我正在编写构造函数的方法,如“游戏”构造函数的“runGame”方法,但是如果需要引用“GameBoard”构造函数的属性,应使用构造函数的名称,如下所示:从另一个构造函数引用对象的属性时应该使用构造函数还是实例?

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

或者我必须首先创建构造函数对象的实例,然后参考像这样的实例。

var newGameBoard = new GameBoard(); 

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

我们不能回答将q uestion,因为你的“to”形式是无效的,所以你在'Game'里面''''this.runGame()'后面的'{''有一个语法错误。这很重要,因为如果我们不知道你的对象是如何组织的,我们不能告诉你如何正确处理它们。 –

+0

构造函数中应该有非常少的代码 - 可能是创建/分配内在可用的相关对象。大多数工作(包括根据需要访问其他对象)发生在方法中。 – user2864740

+0

“到”不是代码的一部分。我试图证明代码正在从一种格式转换为另一种格式。我可能应该把整个第一部分都留下来。我将编辑该问题。 – Drazah

回答

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

延伸阅读:

+0

如果你要替换'prototype'属性引用的对象,一定要正确设置'constructor'。 –

+0

是的!比我的回答更快,更短,更好。 @ T.J.Crowder我不理解你的评论,你的意思是我们应该在原型对象中定义一个构造函数吗?我从来没有这样做,从来没有任何问题,但请赐教 –

+0

@ T.J.Crowder我明白,这是OP的通知,不是吗? –

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

我知道我假设了很多东西,但我不能帮助它,这让我想起我只对参与游戏和gameboards工作的项目:对

+0

如果你要替换'prototype'属性引用的对象,一定要正确设置'constructor'。 –

+0

@Ki jey - 谢谢! – Drazah

1

如果每场比赛有一个游戏键盘,它应该是一个属性:

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

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