无法从外部访问对象中的变量

时间:2015-12-30 10:46:31

标签: javascript

我没有成功地从对象Pong外部访问变量:

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我无法理解为什么可以在start中访问此变量而不是isPlaying。 为什么这和我必须使用什么代码来访问这个变量?为了启用调试,我在onclick事件中添加了调用isPlaying。

1 个答案:

答案 0 :(得分:1)

这是javascript的常见问题之一,this意外更改&#34;#34;。

在回调中,this指向别的东西,而不是你的对象。解决方案之一是在对象中捕获对象引用。

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