2015-12-30 44 views
0

访问变量我并没有从物外傍访问变量演奏成功:不能在对象从外部

Pong = { 
// some other objects 
initialize: function (runner, cfg) { 
    Game.loadImages(Pong.Images, function (images) { 
     this.cfg = cfg; 
     this.runner = runner; 
     this.width = runner.width; 
     this.height = runner.height; 
     this.images = images; 
     this.playing = false; // variable is defined here 
     this.scores = [0, 0]; 
     this.menu = Object.construct(Pong.Menu, this); 
     this.court = Object.construct(Pong.Court, this); 
     this.leftPaddle = Object.construct(Pong.Paddle, this); 
     this.rightPaddle = Object.construct(Pong.Paddle, this, true); 
     this.ball = Object.construct(Pong.Ball, this); 
     this.sounds = Object.construct(Pong.Sounds, this); 
     this.runner.start(); 
    } .bind(this)); 
}, 
// some more functions 
isPlaying: function() { // I added this function to enable for access 
    return this.playing; // here playing is undefined 
}, 

start: function (numPlayers) { 
    if (!this.playing) { // here playing is defined 
     this.scores = [0, 0]; 
     this.playing = true; 
     this.leftPaddle.setAuto(numPlayers < 1, this.level(0)); 
     this.rightPaddle.setAuto(numPlayers < 2, this.level(1)); 
     this.ball.reset(); 
     this.runner.hideCursor(); 
    } 
}, 
// more objects and functions 

这是一个乒乓球比赛。完整的页面是这样的: http://ulrichbangert.de/div/webdesign/javascript/pong.html我不明白为什么这个变量可以在开始访问,而不是在isPlaying。 这是什么和我必须使用什么代码来访问这个变量?为了启用调试,我在onclick事件中添加了调用isPlaying。

+0

放在一起用的jsfiddle你的页面的最小版本的,这样我们就可以轻松帮你 –

回答

1

这是javascript的一个经典问题,this更改“意外”。

在该回调中,this指向其他内容,而不是您的对象。其中一个解决方案是在闭包中捕获对象引用。

initialize: function (runner, cfg) { 
    var that = this; // <= "that" won't change. 
    Game.loadImages(Pong.Images, function (images) { 
     that.cfg = cfg; 
     that.playing = false; 
+0

感谢这个答案,但它不符合我的问题:我的问题是不是该变量意外变化。相反,这是有意的。我的问题是,我不知道如何从对象Pong之外访问该变量。函数初始化中的“this”是什么(它不是Pong,它不是Game),如何从Pong的outsinde访问它? – Sempervivum

+0

'initialize'中的'this'是一个Pong。 loadImages回调函数中的'this'是别的东西(我猜,回调本身)。 –

+0

从这里引用: http://stackoverflow.com/questions/1963357/this-inside-function “这个关键字指的是函数所属的对象,或者如果函数不属于对象,则指向窗口对象。”确认你的陈述:“这在初始化是一个庞”。不幸的是,调试器告诉了另一件事:Pong.playing是未定义的。 – Sempervivum