Reputation: 718
I'm stuck in some part of my code. I created something like model class BoardEx and I want to create Iterator for it, here's some example:
Game.BoardEx = function(params){
...
this.board = Array(cols, rows);
...
}
where Game is the "parent" object of all children "classes". Then I declared Iterator:
Game.BoardEx.prototype.Iterator = function(){
var pos = {x: 0, y: -1};
this.next = function(){
...
return this.board[pos.x][pos.y];
};
Later usage is:
var board = new Game.BoardEx();
var iter = new board.Iterator();
It seems that I can't call this.board
in this scope. Should I use bind
or other method or just can't I call this at all?
Upvotes: 1
Views: 363
Reputation: 276596
You can't access this
of the calling object when you're inside a new
call.
Performing a new
"construct" call changes the context to the newly created object.
Instead, you can use a builder function:
Game.BoardEx.prototype.getIterator = function(){
function Iterator(board){
this.board = board;
this.pos = {x:0, y:-1};
}
Iterator.prototype.next = function(){
return this.board[this.pos.x][this.pos.y];
...
}
return new Iterator(this.board); // create new instance with the board.
}
You can define Iterator
completely externally to the Board, as long as the getIterator function passes a valid board to it. This would also let you call it from the outside and might be more effecient. It will also make instanceof
work but IMO it's really not a big deal.
Upvotes: 2