Jump to content

Uncaught TypeError & Function/Scope Question


adaar
 Share

Recommended Posts

I am having difficulty understanding this and scope in Javascript.  I am attempting to create a dialogue box that pops up during various collisions, and perhaps part of the issue is I am not properly organizing my game. I can use this.showPopup("jump"); in the update function, but I cannot figure out how to call the showPopup function elsewhere, in getItem. I keep getting the error, "Uncaught TypeError: this.showPopup is not a function(…)"  Any help is greatly appreciated.

create: function() {
  ...
  popup = game.add.sprite(window.innerWidth/2, 200, 'box'); 
  ...
  },
update:function (){
  game.physics.arcade.overlap(player, cake, this.getItem);
  },
  getItem:function(player,item) {
    console.log('got ' + item);
    item.kill();
    this.showPopup("test");
  },
  showPopup: function(t){
    popup_timer = game.time.create(false);
    popup_timer.add(1000, this.hidePopup, this);
    popup.text = t;
    tween = game.add.tween(popup.scale).to({x:1,y:1},500, Phaser.Easing.Elastic.Out, true);    
    popup_timer.start();
  },
  hidePopup: function(){
    tween = game.add.tween(popup.scale).to( { x: 0.0, y: 0.0 }, 500, Phaser.Easing.Elastic.In, true);
  }

 

Link to comment
Share on other sites

I suppose the error comes from

  game.physics.arcade.overlap(player, cake, this.getItem);

?

In callback, or event callback, object is often bind in function (as this);

function explanationBind(){
    console.log(this);
}

var lObject = {a:"hello"};
explanationBind.bind(lObject)(); // lObject  in console
explanationBind(); // Window object in console

If you want your object in this method (as this), you have ton bind your object:

  game.physics.arcade.overlap(player, cake, this.getItem.bind(this));

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...