Skip to content

Instantly share code, notes, and snippets.

@jhamon
Created April 20, 2014 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhamon/11112016 to your computer and use it in GitHub Desktop.
Save jhamon/11112016 to your computer and use it in GitHub Desktop.
Shared mutable state among "instances of a class" in javascript.
// 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