1 | initial version |
There are several ways to break down functions into modules in older ES5 codebases:
var ExampleModule = (function() {
var privateVar = 'Hello World';
function privateFunction() {
console.log(privateVar);
}
return {
publicFunction: function() {
privateFunction();
}
};
})();
// 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
// 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
});