Skip to content

Instantly share code, notes, and snippets.

@garethredfern
Last active November 16, 2019 12:33
Show Gist options
  • Save garethredfern/0afa5fe921bbf50aecf42cc6fd139fe8 to your computer and use it in GitHub Desktop.
Save garethredfern/0afa5fe921bbf50aecf42cc6fd139fe8 to your computer and use it in GitHub Desktop.
Basic Module Pattern JavaScript :: 2016-04-10

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment