2017-07-17 99 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; 
}; 
相關問題