How can the the top-most scope can be cached in order to be used deeper in the prototype later, like so:
var Game = function(id){
this.id = id;
};
Game.prototype = {
board : {
init: function(){
// obviously "this" isn't the instance itself, but will be "board"
console.log(this.id);
}
}
}
var game = new Game('123');
game.board.init(); // should output "123"
Well now that I think about it, I can use apply
/call
and pass the context...
game.board.init.apply(game);
As you only have one instance of the board
object, there is no way for it to know what you used to access it. Using game.board
or Game.prototype.board
to access the object gives exactly the same result.
If you don't want to create one board
object for each Game
instance, you have to tell the board
object which Game
object it should consider itself to belong to for each call:
game.board.doSomething(game);
or:
Game.prototype.board.doSomething(game);
To create one board for each Game
instance, make a constructor for Board
, and make the board object aware of the Game
instance that it belongs to:
function Game(id) {
this.id = id;
this.board = new Board(this);
}
Game.prototype = {
};
function Board(game) {
this.game = game;
}
Board.prototype = {
init: function(){
console.log(this.game.id);
}
};
var game = new Game('123');
game.board.init(); // outputs "123"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With