Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Running collection of IIFE Patterns
(function( window, document, undefined ){
})( this, this.document );
(function( global, undefined ){
})( this );
// miketaylr
(function( win, doc ){
// SCREW U UNDEFINED
})( window, document );
// ralphholzmann
(function poll() {
/* Lots of stuffs here */
if ( cssIsReady ) {
cssCallback();
} else {
setTimeout( poll, 50 );
}
})();
// mennovanslooten
new function() {
// No arguments though
}
// addyosmani
(function(){
arguments.callee();
}());
(function(){
/* do stuff */
}());
// rmurphey
!function(){
// Note that I don't like this one, but it does exist :)
}();
@miketaylr
Copy link

miketaylr commented Apr 28, 2011

I like:

(function(win,doc){

})(window,document)

SCREW U UNDEFINED

@ralphholzmann
Copy link

ralphholzmann commented Apr 28, 2011

I enjoy recursive IIFEs, we use them to poll for css callbacks in yepnope.js

(function poll() {
  /* Lots of stuffs here */
  if ( cssIsReady ) {
    cssCallback();
  } else {
    setTimeout( poll, 50 );
  }
})();

Not sure if this is technically an IIFE because of the "poll" identifier, but it beats using arguments.callee.

<3z

@mennovanslooten
Copy link

mennovanslooten commented Apr 28, 2011

new function() {
    // No arguments though
}

@addyosmani
Copy link

addyosmani commented Apr 28, 2011

Including just because it technically counts, even if ralph's kicks its ass a little ; )

(function(){
arguments.callee();
}());

and I guess this is one of the more common immediately invoked variations I use:
(function(){
/* do stuff */
}());

No funky syntax highlighting. I'm commenting from a phone and Im lazy.

@rmurphey
Copy link

rmurphey commented Apr 29, 2011

!function(){ /* ... */ }()

Note that I don't like this one, but it does exist :)

@sindresorhus
Copy link

sindresorhus commented May 1, 2011

Here are some more:

null,function(){ /* ... */ }()

this,function(){ /* ... */ }()

666,function(){ /* ... */ }()

'☹',function(){ /* ... */ }()

-function(){ /* ... */ }()

+function(){ /* ... */ }()

|function(){ /* ... */ }()

^function(){ /* ... */ }()

>>>function(){ /* ... */ }()

~function(){ /* ... */ }()

-([[{}||{}]])>>>function(){ /* ... */ }()

None of them should be used though.

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