Skip to content

Instantly share code, notes, and snippets.

@jaspervalero
Created March 5, 2015 05:12
Show Gist options
  • Select an option

  • Save jaspervalero/53f38d9b413caa5846ca to your computer and use it in GitHub Desktop.

Select an option

Save jaspervalero/53f38d9b413caa5846ca to your computer and use it in GitHub Desktop.
ES5 example of 'this' scope using 'self' variable
function Gamer() {
// Store value of this in a variable
var self = this; // Some people use that or _this
self.playTime = 0;
// trackPlayTime() will now correctly auto increment every second
setInterval( function trackPlayTime() {
// Because we're using a variable we don't have to worry about the dynamic value of this in the new function scope
self.playTime++;
// Correctly out
console.log( self.playTime );
}, 1000 );
}
var gamer = new Gamer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment