【发布时间】:2016-06-01 05:20:01
【问题描述】:
我正在使用 Phaser.js 开发一个 JavaScript 游戏,但我遇到了一些范围问题,我不知道如何解决它。
当玩家获胜时,ResultPanel 会出现分数和一些按钮。玩家可以按下按钮进入下一关或重置等。处理返回/重置/下一步的代码在原型函数中,但在调用构造函数时尚未定义(?)。
现在,当我按下按钮时,函数doBtnBack 永远不会被调用。
我究竟做错了什么?这样做的正确方法是什么?
// level complete panel constructor
ResultPanel = function(game, stars) {
this.game = game;
// display how many yellow stars
var star1 = stars > 0 ? 'star_yellow' : 'star_grey';
var star2 = stars > 1 ? 'star_yellow' : 'star_grey';
var star3 = stars > 2 ? 'star_yellow' : 'star_grey';
// add text and stars
this._panelCaption = this.game.add.bitmapText(144, 12, 'bigrigsfont', 'you are winner!', 48);
this._panelStar1 = this.game.add.sprite(300-160, 144, 'buttonicon', star1);
this._panelStar2 = this.game.add.sprite(300, 144, 'buttonicon', star2);
this._panelStar3 = this.game.add.sprite(300+160, 144, 'buttonicon', star3);
// add button icons
// NOTE: below code runs but something is wrong because
// this.doBtnBack this.doBtnReset etc. is undefined
this.btnBack = this.game.add.button(300-100, 300, 'buttonicon', this.doBtnBack, this, 'back_grey', 'back_hl');
this.btnReset = this.game.add.button(300, 300, 'buttonicon', this.doBtnReset, this, 'reset_grey', 'reset_hl');
this.btnNext = this.game.add.button(300+100, 300, 'buttonicon', this.doBtnNext, this, 'next_grey', 'next_hl');
};
ResultPanel.prototype.doBtnBack = function() {
console.log('Panel button BACK pressed') // never reaches here
};
ResultPanel.prototype.doBtnReset = function() {
console.log('Panel button RESET pressed');
};
ResultPanel.prototype.doBtnNext = function() {
console.log('Panel button NEXT pressed');
};
我也试过这个,但是会报错Uncaught TypeError: this.doBtnBack is not a function
this.btnBack = this.game.add.button(300-100, 300, 'buttonicon', function(){this.doBtnBack();}, this, 4, 0, 8);
【问题讨论】:
-
看不到
this.game的定义在哪里(应该是未定义的)?您可以使用来自参数的game(不带this),或者在ResultPanel的开头分配this.game = game。 -
我尝试只在问题中添加相关代码但忘记添加
this.game = game;,现在添加 -
有可能在没有
new的情况下调用ResultPanel?你能在构造函数中创建console.log(this)吗? -
使用了
new关键字,所以当我在构造函数中将this登录到控制台时,它会按预期显示ResultPanel > _bounds: c.Rectangle _cacheAsBitmap: false etc.
标签: javascript phaser-framework