Jump to content

Best Practice for Scope


jflowers45
 Share

Recommended Posts

Got a question about best practices.  in the function where dragging begins I'd like to reference other variables that are in the same game state.  

 

someSprite.events.onDragStart.add(this.dragStarting);

 

dragStarting(item) {
//in this function I want to access variables from the current State but 'this' no longer refers to the game state
}
 
i've gotten around this as follows:
 
someSprite.activeState=this;
someSprite.events.onDragStart.add(this.dragStarting);
dragStarting(item) {
//reference item.activeState here
}
 
This works fine but I'm wondering whether this is the standard approach or if there's a better way.
 
Thanks
-Joe

 

Link to comment
Share on other sites

xerver made an interesting post about this in the Pixi forum: http://www.html5gamedevs.com/topic/3892-getting-mixed-up-using-this-scopes/?p=24684

 

I've almost exclusively stuck with using Function.prototype.bind to manage scope, but it seems like you have to be careful (and indeed the bind process is one of the most time consuming if I profile my games). Otherwise, keeping a reference to the object you want a layer above the callback's scope is fine.

Link to comment
Share on other sites

someSprite.events.onDragStart.add(this.dragStarting);

 

dragStarting(item) {
//in this function I want to access variables from the current State but 'this' no longer refers to the game state
}

 

You should define the scope in your onDragStart line, like so:

someSprite.events.onDragStart.add(dragStarting, this);

This sets the context in which dragStarting is run, giving you full access to that context (in your case 'this').

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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