adaar

Uncaught TypeError & Function/Scope Question

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);
  }

 

Share this post


Link to post
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));

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.