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

标签 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。

最佳答案

这是 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;

关于javascript - 无法从外部访问对象中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34527952/

相关文章:

javascript - 如何制作一个react + d3堆积条形图分组?

javascript - 使用jquery添加和删除表中的行

javascript - kendo javascript t.find 不是一个函数

javascript - jQuery:.load() 方法替换目标选择器内容或附加到它?

javascript - 将 Excel 公式转换为 Javascript D3.js

javascript - 将输入参数传递给 .click 事件

javascript - 如何在 Node.js Express 中让我的 session 最后跨子域?

javascript - string.charAt() 返回 0

javascript - 使用 AWS 的 getObject 在浏览器中显示图像

javascript - .click 将一段 json 添加到面板中