Last active
December 10, 2015 18:58
-
-
Save zhannes/4478528 to your computer and use it in GitHub Desktop.
`this` in javascript, scoping, execution context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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