Created
March 5, 2015 05:12
-
-
Save jaspervalero/53f38d9b413caa5846ca to your computer and use it in GitHub Desktop.
ES5 example of 'this' scope using 'self' variable
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() { | |
| // 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