Last active
August 29, 2015 14:16
-
-
Save jaspervalero/0161b975e531666566fb to your computer and use it in GitHub Desktop.
ES5 this Example
This file contains hidden or 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
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