Skip to content

Instantly share code, notes, and snippets.

@zhannes
Last active December 10, 2015 18:58
Show Gist options
  • Save zhannes/4478528 to your computer and use it in GitHub Desktop.
Save zhannes/4478528 to your computer and use it in GitHub Desktop.
`this` in javascript, scoping, execution context
/* how to bind `this` for callbacks, good example here too:
http://ejohn.org/apps/learn/#84
*/
var uiThing = {
parseResponse : function(data){
this.data = data;
this.renderUI()
},
renderUI : function(){ /* more code */ }
};
// remember to bind your callbacks to the proper context
$.ajax({
type: 'GET',
url: 'http://api.com/your/endpoint',
complete: uiThing.parseResponse.bind( uiThing )
});
/* Without the bind, Fail:
Uncaught TypeError: Object #<Object> has no method 'renderUI'.
why?
When your callback ran, `this` inside your callback referenced the global context, aka Window.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment