Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created July 27, 2012 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhulse/3186282 to your computer and use it in GitHub Desktop.
Save mhulse/3186282 to your computer and use it in GitHub Desktop.
Javascript: IIFE example...
var GO = (function(go) {
go = go || {};
go.init = function(x) {
console.log(x);
};
go.hello = function(msg) {
console.log('Hello: ' + msg);
};
return go;
}(GO || {}));
GO.init('blah');
GO.hello('Billy');
var GO = (function(go) {
// We've already determined if GO is defined, so no need to do the same thing here, right?
go.init = function(x) {
console.log(x);
};
go.hello = function(msg) {
console.log('Hello: ' + msg);
};
return go;
}(GO || {})); // Pass GO if defined, otherwise pass empty object.
var GO = (function(go) {
go = go || {}; // Do our check here.
go.init = function(x) {
console.log(x);
};
go.hello = function(msg) {
console.log('Hello: ' + msg);
};
return go;
}(GO)); // Cleaner! Thanks @preaction! :)
GO.init('blah');
GO.hello('Billy');
@mhulse
Copy link
Author

mhulse commented Jul 27, 2012

From @preaction via IRC:

in that exact instance you could remove either, but removing the outer one is safer, because it's closer to where the problem would occur if go was ever not an object

Thanks!!!!!

@mhulse
Copy link
Author

mhulse commented Oct 8, 2012

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