Ask Your Question
4

How can one break down functions into modules in older ES5 codebases?

asked 2022-05-15 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-01-11 10:00:00 +0000

ladyg gravatar image

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
});
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-15 11:00:00 +0000

Seen: 9 times

Last updated: Jan 11 '23