原型:“这个”的深度范围访问实例的范围 [英] 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"
更新:
现在我考虑一下,我可以使用 apply
/ call
并传递上下文......
update:
Well now that I think about it, I can use apply
/call
and pass the context...
game.board.init.apply(game);
推荐答案
因为你只有一个<$ c的实例$ c> board 对象,它无法知道您用来访问它的内容。使用 game.board
或 Game.prototype.board
来访问该对象会得到完全相同的结果。
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.
如果您不想为每个游戏
board 对象>例如,你必须告诉 board
对象它应该认为自己属于每个调用的 Game
对象:
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);
或:
Game.prototype.board.doSomething(game);
编辑:
创建一块板对于每个 Game
实例,为 Board
创建一个构造函数,并使board对象知道游戏
它所属的实例:
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"
这篇关于原型:“这个”的深度范围访问实例的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!