[英]javascript reference to prototype function is undefined in constructor
[英]Reference a prototype function in the constructor, how?
我正在使用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);
好的,实际上我在所有对象上都使用了MyGame前缀/命名空间,因为在此代码示例中也使用了它 。 我承认我不太了解MyGame.
精确地做。
所以我的代码实际上看起来像这样:
var MyGame = {};
MyGame.Bootup = function() {
//etc.
MyGame.GameState = function() {
create: function() {
var panel = new MyGame.ResultPanel(this, 3);
}
};
并查看下面的面板对象代码。 现在,如果我删除所有MyGame.
从下面的代码中删除,但将其保留在上面的代码中(除非在var panel = new ResultPanel(this,3)“中,然后它才能正常工作(?)。不知道为什么。
// level complete panel constructor
MyGame.ResultPanel = function(game, stars) {
this.game = game;
// etc.
};
MyGame.ResultPanel.prototype.doBtnBack = function() {
console.log('Panel button BACK pressed') // never reaches here
};
MyGame.ResultPanel.prototype.doBtnReset = function() {
console.log('Panel button RESET pressed');
};
MyGame.ResultPanel.prototype.doBtnNext = function() {
console.log('Panel button NEXT pressed');
};
// level complete panel constructor
MyGame.GameState = function() {
create: function() {
var panel = new MyGame.ResultPanel(this, 3);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.