Skip to content

Instantly share code, notes, and snippets.

@odiak
Created March 1, 2011 00:08
Show Gist options
  • Save odiak/848334 to your computer and use it in GitHub Desktop.
Save odiak/848334 to your computer and use it in GitHub Desktop.
using closure.
var c = new Counter();
c.add(); // 1
c.get(); // 1
c.add(); // 2
var n;
n = c + 1; // n == 3
var Counter = function(){
var count = 0;
var add = function(){
count += 1;
return getCount();
};
var get = function(){
return getCount();
};
var getCount = function(){
return count ? count : 0;
};
return function(){
this.add = add;
this.get = get;
this.valueOf = get;
};
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment