首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >赋值后未定义的变量

赋值后未定义的变量
EN

Stack Overflow用户
提问于 2015-09-04 01:20:30
回答 2查看 474关注 0票数 0

我是一个初级的javascript程序员。我找不到为什么以下函数中的winXWinY变量有undefined值的原因:

代码语言:javascript
复制
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);
}

这里发生了什么以及如何修复它?

EN

回答 2

Stack Overflow用户

发布于 2015-09-04 01:24:41

this的值取决于调用上下文。

您可能需要绑定有问题的对象,大致如下:

代码语言:javascript
复制
this.p[i][j].events.onInputDown.add(myMethod.bind(this), this);

(但由于您的代码目前的立场,这将有相同的问题)或依赖于任何有问题的框架提供的绑定方式。

欢迎来到JS。

票数 1
EN

Stack Overflow用户

发布于 2015-09-04 01:25:34

在JS上使用this打开了一个痛苦的世界。您应该避免它,直到您真正确定how it works或将其重命名为您作用域中的其他名称:

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32381859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档