Skip to content

Instantly share code, notes, and snippets.

@paulirish
Created February 26, 2010 17:16
Show Gist options
  • Save paulirish/315916 to your computer and use it in GitHub Desktop.
Save paulirish/315916 to your computer and use it in GitHub Desktop.
// everyone's new favorite closure pattern:
(function(window,document,undefined){ ... })(this,this.document);
// when minified:
(function(w,d,u){ ... })(this,this.document);
// which means all uses of window/document/undefined inside the closure
// will be single-lettered, so big gains in minification.
// it also will speed up scope chain traversal a tiny tiny little bit.
// additionally it protects against the case where someone does `undefined = true`
// tech details:
(function(){ })() // is a self executing anonymous function
// and when we
(function(myname){ })('paul') // we're just bypassing a var declaration at the top
// and then in this case, `this` is always the global object when in global scope so
// we can safely use it.
// and a horribley awesome idea. duck punch to switch up the args passed in on all ready functions
(function(oReady){
$.fn.ready = function(fn){
return oReady.call(this, function(){ fn.call(this, $, window, document); });
};
})($.fn.ready);
// which enables
$(function($,window,document,undefined){ alert(document) })
// temp01 ftw. thx!
@SlexAxton
Copy link

wowy zowy thats neat

@mfolnovic
Copy link

could it be used for some other constants, like true, false ? and how good idea is that ?

@paulirish
Copy link
Author

I've seen people do it.. like a var TRUE = true or even var TRUE = !0 but i think that's kinda overboard.

@mfolnovic
Copy link

that is useless, but what about:
(function(TRUE, FALSE) {
})(true,false)

which would minify to:
(function(a,b){})(true,false);

also, seems weird to me that closure compiler transforms !0 back to true, 1! to false...

@paulirish
Copy link
Author

Hah, join the party. :) I think someone filed a bug against compiler for that. heh.

Yeah i think the minification benefits are nice, but having TRUE and FALSE all throughout your code is really distracting and not beautiful.. so i wouldnt recommend it, but it certainly might have advantages.

@mfolnovic
Copy link

and it would be really weird if we could do true=false, but it wouldn't be so ugly then... :)

and I found this discussion about !0 and !1, http://groups.google.com/group/closure-compiler-discuss/browse_thread/thread/90bcf1eeeb7589d1, seems like it's slower... I also benchmarked it, and it seems slower for ~4.73%

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