Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

A singleton function?

Posted on November 27, 2007 20:51 Tagged with javascript.

This function allows you to make sure a function gets run only once. I’ve been trying to come up with a better name for it than singletonize, because it doesn’t really have anything to do with singletons. I’m thinking that people before me must have done the same thing and come up with a better name. Is this a common pattern, and what is it called?

Function.prototype.singletonize = function(){
  var fn = this,
      hasRun = false;

  return function(){
    if (!hasRun) {
      hasRun = true;
      return fn.apply(this, arguments);
    }
  };
}

Usage:

var o = {
  foo: 'bar',
  bar: (function(){
    print(this.foo);
  }).singletonize()
};

o.bar(); //prints "bar"
o.bar(); //does nothing

Never trust a man with no shirt on