prototype:访问实例范围的"this"深度范围

vsy*_*ync 6 javascript prototype

如何才能缓存最顶层的范围,以便以后在原型中更深入地使用,如下所示:

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"
Run Code Online (Sandbox Code Playgroud)

更新:

那么现在我考虑一下,我可以使用apply/ call并传递上下文...

game.board.init.apply(game);
Run Code Online (Sandbox Code Playgroud)

Ste*_*hen 1

不存在“原型的更深处”这样的事情。“this”将始终是您调用它的对象,除非通过回调或各种重新绑定方式进行更改。如果你分解你的概念并将它们链接在一起,你会减少理智的损失:

Board = function (game) {
    this.game = game;
}

Board.prototype.init = function () {
    console.log(this.game.id);
}

Game = function () {
    this.id = 123;
    this.board = new Board(game);
}

Game.prototype = {};
Run Code Online (Sandbox Code Playgroud)

或者,如果你一心想让它们都使用相同的基础,你可以做一些疯狂的黑客,比如..

Game = function () {
    this.id = 123;
    var self = this;
    for(var p in this.board) {
        var property = this.board[p];
        if(typeof property == 'function') {
            this.board[p] = function (method) {
                return function () {
                    method.apply(self, arguments);
                }
            }(property)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这完全是一种黑客行为,它会让你的同事讨厌你。(如果您使用的是 underscore 库,有一个 bindAll 函数可以帮助解决这个问题)