Created
April 20, 2014 11:42
-
-
Save jhamon/11112016 to your computer and use it in GitHub Desktop.
Shared mutable state among "instances of a class" in javascript.
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
// In this gist, I explain how to achieve mutable shared state | |
// between "instances of a class", i.e. objects with a shared | |
// prototype. This mimics how "class variables" are used | |
// in other languages with classical inheritance. | |
// Not something you want to do all the time, obviously, but it could | |
// be handy in some situations. | |
function Cat() { | |
// increment the class variable each time a constructor is used. | |
this.constructor.prototype.catsSoFar += 1; | |
} | |
Cat.prototype.constructor = Cat; | |
Cat.prototype.catsSoFar = 0; | |
// All instances will see the change in this variable. | |
garfield = new Cat(); | |
garfield.catsSoFar // 0 | |
tom = new Cat(); | |
felix = new Cat(); | |
garfield.catsSoFar // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment