Published 4/10/2016 ยท 1 min read
Tags: javascript
Basic Module Pattern JavaScript
Wrap your code in an immediately invoked function expression (IFFE). It runs immediately when you create it and has no name. Normally you would create a IFFE like this:
(function () {
// your code
})();
It is common practice to remove the outer wrapping parenthesis and use a ! or + at the start of the anonymous function:
!(function () {
function foo() {
console.log("foobar");
}
foo();
})();
You can pass a variable into the IFFE so that it can be used within its local scope. Here I am passing in the underscore library using _ to be used within the module.
!(function (underscore) {
console.log(underscore.VERSION);
})(_);
You can name the passed in variable (parameter) whatever you like so while you would normally use the underscore library by using _ you can now use it within the local scope using underscore. variable.
Another use might be to pass in the window object and create a variable called global within your IFFE. Now you can access the global scope by using the global variable.
var bar = "foo";
!(function (global) {
console.log(global.bar); // foo
})(window); Related Articles
- Compressed NFTs: Collections, Verification, and Building a Claim Page
Taking our cNFT minting system to production: creating verified collections, building a web-based claim flow, and preparing for mainnet deployment.
- Building Compressed NFTs on Solana with Generative SVG Art
A practical guide to creating and minting compressed NFTs (cNFTs) on Solana using Metaplex Bubblegum, with animated SVG artwork generated from wallet addresses.
- Learn Svelte & SvelteKit: Course Overview
A complete beginner's guide to Svelte and SvelteKit. From reactivity basics to full-stack applications, learn the framework that compiles away.