Skip to content

Instantly share code, notes, and snippets.

@jaspervalero
Last active August 29, 2015 14:16
Show Gist options
  • Save jaspervalero/0161b975e531666566fb to your computer and use it in GitHub Desktop.
Save jaspervalero/0161b975e531666566fb to your computer and use it in GitHub Desktop.
ES5 this Example
function Gamer() {
// 'this' refers to Gamer
this.playTime = 0;
// We think trackPlayTime() will update a gamer's playtime every second
setInterval( function trackPlayTime() {
// But we're wrong because trackPlayTime() creates it's own version of 'this'
this.playTime++;
// Outputs NaN, because this.playTime was never cast as an integer in this scope
console.log( this.playTime );
}, 1000 );
// Outputs 0, because this.playTime was never incremented in this scope
console.log( this.playTime );
}
var gamer = new Gamer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment