Javascript 引用对象时应该使用构造函数还是实例';来自另一个构造函数的属性?
当我编写构造函数的方法时,比如“Game”构造函数的“runGame”方法,如果我需要引用“GameBoard”构造函数的属性,我是否应该使用构造函数的名称,如下所示:Javascript 引用对象时应该使用构造函数还是实例';来自另一个构造函数的属性?,javascript,oop,object,constructor,Javascript,Oop,Object,Constructor,当我编写构造函数的方法时,比如“Game”构造函数的“runGame”方法,如果我需要引用“GameBoard”构造函数的属性,我是否应该使用构造函数的名称,如下所示: function Game(){ this.runGame(){ var someProp = GameBoard.otherProp; } } 或者我必须先创建构造函数对象的实例,然后像这样引用该实例 var newGameBoard = new GameBoard(); function Game(
function Game(){
this.runGame(){
var someProp = GameBoard.otherProp;
}
}
或者我必须先创建构造函数对象的实例,然后像这样引用该实例
var newGameBoard = new GameBoard();
function Game(){
this.runGame(){
var someProp = newGameBoard.otherProp;
}
}
如果我以正确的方式理解了您的问题,那么您需要的是合成,并且您需要在构建期间注入关联实例:
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);
进一步阅读:
游戏板在您的逻辑中属于游戏
,我会这样做
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如果每个游戏都有一个游戏板,它应该是一个属性:
function Game(){
this.board=new Board();
}
Game.prototype.runGame=function(){//real inheritance
var someProp = this.board.otherProp;
};
我们无法回答此问题,因为您的“to”形式无效,您在{
this.runGame()之后出现语法错误
内部游戏
。这很重要,因为如果我们不知道你的对象是如何组织的,我们就无法告诉你如何正确处理它们。构造函数中应该只有很少的代码——也许是创建/分配本质上可用的相关对象。大多数都有效(包括根据需要访问其他对象)发生在方法中不是代码的一部分。我试图显示代码正在从一种格式转换为另一种格式。我可能应该将第一部分全部保留下来。我将编辑问题。@Drazah:问题中的代码仍然是语法错误。很高兴有人尝试提供帮助(尽管我认为他们应该等到问题弄清楚了再说),但实际上,代码没有语法错误,因此我们知道您在做什么是起点。如果您要替换prototype
属性引用的对象,请确保正确设置构造函数。是的!比我的答案更快、更短、更好。@T.J.Crowder我不理解您的评论,您的意思是我们应该这样做吗在prototype对象中定义构造函数?我从来没有这样做过,从来没有遇到过任何问题,但请启发一下me@T.J.Crowder我知道这是OP的通知,不是吗?@MatíasFidemraizer:嗯,不是真的。如果你想举个例子,鼓吹做他们不做的事情(替换原型属性),显示是否正确操作很重要。@KiJéy:请参阅:如果要替换prototype
属性引用的对象,请确保正确设置构造函数。@kijey-谢谢!