Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are several ways to break down functions into modules in older ES5 codebases:

  1. Using the Immediately-Invoked Function Expression (IIFE) pattern:
var ExampleModule = (function() {
  var privateVar = 'Hello World';

  function privateFunction() {
    console.log(privateVar);
  }

  return {
    publicFunction: function() {
      privateFunction();
    }
  };
})();
  1. Using the CommonJS module format:
// In file math.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add: add,
  subtract: subtract
};
// In file app.js
var math = require('./math');

console.log(math.add(1, 2)); // 3
console.log(math.subtract(3, 2)); // 1
  1. Using the Asynchronous Module Definition (AMD) format:
// In file math.js
define(function() {
  function add(a, b) {
    return a + b;
  }

  function subtract(a, b) {
    return a - b;
  }

  return {
    add: add,
    subtract: subtract
  };
});
// In file app.js
require(['math'], function(math) {
  console.log(math.add(1, 2)); // 3
  console.log(math.subtract(3, 2)); // 1
});