简体   繁体   中英

Javascript variable scope and inheritance

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM