Skip to content

Instantly share code, notes, and snippets.

@indutny
Created May 10, 2011 11:26
Show Gist options
  • Save indutny/964299 to your computer and use it in GitHub Desktop.
Save indutny/964299 to your computer and use it in GitHub Desktop.
function thatYouWantToExport() {
};
if (typeof exports === 'undefined') {
window.myFn = thatYouWantToExport;
} else {
exports.myFn = thatYouWantToExport;
}
@heapwolf
Copy link

;(function(env) { return env.myLib = function myLib() { /.../ }; }(this.exports || this));

this provides a closure for encapsulation/variable safety, environment detection and passes the execution context pointer in as a parameter that can be obfuscated.

@indutny
Copy link
Author

indutny commented May 10, 2011

I don't like usage of this. Btw, you missed one right-closing parenthesis and have one excessive

@heapwolf
Copy link

;(function(env) { return env.myLib = function myLib() { /.../ }; } (this.exports || this) );

actually this is the correct number of parenthesis, this is called a IIFE (Immediately Invoked Function Expression) alternatively you can write

;(function(env) { return env.myLib = function myLib() { /.../ }; })(this.exports || this);

but it will not validate. alternatively you could do this,

;(function(env) { return env.myLib = function myLib() { /.../ }; })(window || module.exports);

@indutny
Copy link
Author

indutny commented May 10, 2011

Oh, sorry. You're right.

Missed that you'd started with ;(

@heapwolf
Copy link

;(function(env) { return env.myLib = function myLib() { /.../ }; }(window || module.exports));

seems like a pretty nice solution if you dont like this.

@indutny
Copy link
Author

indutny commented May 10, 2011

This will throw ReferenceError: window is not defined

@heapwolf
Copy link

oh yeah, i think thats why i opted for |this| instead.

@heapwolf
Copy link

if you come up with a clever way to not use | this | let me know ;)

@indutny
Copy link
Author

indutny commented May 10, 2011

this.exports || this === (typeof exports === 'undefined' ? window : exports)

@heapwolf
Copy link

hehe, my original code is looking pretty good at this point ;)

@indutny
Copy link
Author

indutny commented May 10, 2011

Your truth :) Just like my code more than yours :D

@heapwolf
Copy link

hehe, thats how it is, everyone prefers their own code ;)

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