Skip to content

Instantly share code, notes, and snippets.

@THEtheChad
Created May 3, 2012 16:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save THEtheChad/2586972 to your computer and use it in GitHub Desktop.
Save THEtheChad/2586972 to your computer and use it in GitHub Desktop.
Defers execution of the callback until exec is run. At that point, all future calls are executed immediately.
function Defer(callback){
if(!this instanceof Defer)
return new Defer(callback);
var queue = []
, callback = callback
, slice = Array.prototype.slice
, changeling = function(){
queue.push({
'context': this,
'args' : slice.call(arguments, 0)
});
}
, wrapper = function(){
changeling.apply(this, slice.call(arguments, 0));
}
;//var
wrapper.exec = function(){
var call;
while(call = queue.pop()){
callback.apply(call.context, call.args);
}
changeling = callback;
}
return wrapper;
}
@kputnam
Copy link

kputnam commented May 3, 2012

var func = function(x) { return x };
func.hello = function(who) { return "hey baby, " + who; }

func(10) // => 10
func.hello("chad") // => "hey baby, chad"

@kputnam
Copy link

kputnam commented May 3, 2012

var func = (function() {
  var privateData = 0;

  var _func = function(x) { privateData ++; return x; };
  _func.hello = function(who) { return "you called " + privateData + " times"; }

  return _func;
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment