我是一个初级的javascript程序员。我找不到为什么以下函数中的winX和WinY变量有undefined值的原因:
var game = new Phaser.Game(
800,
600,
Phaser.AUTO,
'game',
{ init: init,
preload: preload,
create: create,
update: update,
randomizeWin: randomizeWin,
myMethod: myMethod
}
);
function init() {
this.sss=56;
this.marginX=150;
this.marinY=100;
}
function preload() {
var wood = game.load.image('wood', 'assets/wood.jpg');
randomizeWin();
console.log(this.winY);
}
function create() {
this.p=[];
for(var i=0;i<3;i++) {
this.p[i]=[];
for(var j=0;j<3;j++){
this.p[i][j]= game.add.sprite(this.marginX+i*170, this.marinY+j*170, 'wood');
this.p[i][j].scale.x=0.2;
this.p[i][j].scale.y=0.2;
this.p[i][j].anchor.setTo(.5,.5);
this.p[i][j].inputEnabled = true;
this.p[i][j].input.useHandCursor = true;
this.p[i][j].events.onInputDown.add(myMethod, this);
}
}
}
function update() {
}
function myMethod(sprite) {
console.log(this.p[this.winX][this.winY]==sprite);// winX is undefined here why??
if(this.p[this.winX][this.winY]==sprite){
game.add.tween(sprite.scale).to ({
x: sprite.scale.x * -1,
// y: sprite.scale.y * -1
}, 1000, Phaser.Easing.Bounce.Out, true);
}
}
function randomizeWin() {
console.log("rand");
this.winX = Math.floor(Math.random() * 3);
this.winY = Math.floor(Math.random() * 3);
}这里发生了什么以及如何修复它?
发布于 2015-09-04 01:24:41
this的值取决于调用上下文。
您可能需要绑定有问题的对象,大致如下:
this.p[i][j].events.onInputDown.add(myMethod.bind(this), this);(但由于您的代码目前的立场,这将有相同的问题)或依赖于任何有问题的框架提供的绑定方式。
欢迎来到JS。
发布于 2015-09-04 01:25:34
在JS上使用this打开了一个痛苦的世界。您应该避免它,直到您真正确定how it works或将其重命名为您作用域中的其他名称:
var self = this;
function create() {
self.p = [];
//etc
}
function randomizeWin(){
self.winX = Math.floor(Math.random() * 3);
self.winY = Math.floor(Math.random() * 3);
}
function myMethod(sprite){
console.log(self.p[self.winX][self.winY]==sprite);
}https://stackoverflow.com/questions/32381859
复制相似问题