gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:02:38 24 4
gpt4 key购买 nike

我没有成功访问从对象 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com