Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prototype: deep scope of "this" to access instance's scope

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"

update:

Well now that I think about it, I can use apply/call and pass the context...

game.board.init.apply(game);
like image 424
vsync Avatar asked May 11 '13 22:05

vsync


1 Answers

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

Edit:

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"
like image 196
Guffa Avatar answered Sep 30 '22 05:09

Guffa