Skip to content

Instantly share code, notes, and snippets.

@wuweiweiwu
Forked from branneman/1-globals.js
Created May 26, 2018 22:35
Show Gist options
  • Save wuweiweiwu/5560889ce0ffbdcb26e4cc1ebc690a65 to your computer and use it in GitHub Desktop.
Save wuweiweiwu/5560889ce0ffbdcb26e4cc1ebc690a65 to your computer and use it in GitHub Desktop.
A history of different JavaScript module formats
/**
* Globals
*/
var Carrousel = function(elem) { this.init() };
Carrousel.prototype = { init: function() {} };
new Carrousel();
/**
* Namespacing
* - No globals (only the namespace variable itself is global)
*/
window.NS = {} || window.NS;
NS.Carrousel = function(elem) { this.init() };
NS.Carrousel.prototype = { init: function() {} };
new NS.Carrousel();
/**
* IIFE (immediately-invoked function expression)
* - No globals
*/
(function(){
var Carrousel = function(elem) { this.init() };
Carrousel.prototype = { init: function() {} };
new Carrousel($('.carrousel'));
}());
/**
* Module Pattern
* - No globals (the entrypoint code is often wrapped inside an IIFE as well)
* - Import dependencies, synchronously
* - Export module
*/
var Carrousel = (function($) {
var Carrousel = function(elem) { this.init() };
Carrousel.prototype = { init: function() {} };
function privateMethod() {};
return Carrousel;
}(jQuery));
/**
* CommonJS
* Used inside Node.js, where sync is required.
* - No globals (all modules are wrapped inside an anonymous function)
* - Import dependencies synchronously with `require()` function
* - Export module by assigning to `module.exports` variable
*/
var $ = require('jQuery');
var Carrousel = function(elem) { this.init() };
Carrousel.prototype = { init: function() {} };
function privateMethod() {};
module.exports = Carrousel;
/**
* AMD (Asynchronous Module Definition)
* Used inside browsers (via Require.js for example), where async is often required.
* - No globals (all modules are wrapped inside an anonymous function)
* - Import dependencies, asynchronously (http-call)
* - Export module
*/
define(['jQuery'], function($) {
var Carrousel = function(elem) { this.init() };
Carrousel.prototype = { init: function() {} };
function privateMethod() {};
return Carrousel;
});
/**
* ES2015 Modules
* This syntax is often transpiled to ES5 for systems without support. The transpilation target is either CommonJS or AMD.
* - No globals
* - Specification is syntax-only (doesn't define sync or async behaviour)
* - Syntax reads synchronously
* - Import dependencies with `import` statement
* - Export module with `export` statement
*/
import $ from 'jQuery';
var Carrousel = function(elem) { this.init() };
Carrousel.prototype = { init: function() {} };
function privateMethod() {};
export default Carrousel;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment