Skip to content

Instantly share code, notes, and snippets.

@willmcneilly
Last active August 29, 2015 14:07
Show Gist options
  • Save willmcneilly/4ab7bec6183f7bd554d0 to your computer and use it in GitHub Desktop.
Save willmcneilly/4ab7bec6183f7bd554d0 to your computer and use it in GitHub Desktop.
Overriding valueOf in custom objects
function Counter(){
this.count = 0;
}
Counter.prototype.incr = function() {
this.count++;
}
Counter.prototype.valueOf = function() {
return this.count;
}
c = new Counter();
c.incr(); // this.count now === 1;
console.log(c.count); // will return 1;
console.log(c + 2); // will return 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment