Introduction to JavaScript Modular Applications
var robot = {
name: 'ED-209',
talk: function () {
console.log("I'm " + this.name + ", please put down your weapon. You have twenty seconds to comply.");
},
walk: function () {
console.log("Swooosh, Swooosh!")
},
shoot: function (target) {
target = target || "";
console.log("Pew pew pew " + target);
}
};
ExampleConstructor Pattern
function Robot(opts) {
opts = opts || {
name: 'Sonny',
type: 'NS5'
};
this.name = opts.name;
this.type = opts.type;
}
Robot.prototype.introduce = function () {
console.log('Hello my name is ' + this.name);
return this;
};
Robot.prototype.talk = function () {
console.log('What does this action signify? ;)');
return this;
};
ExampleModule Pattern
var robot = (function () {
var forbbidenActions = ['harm', 'kill', 'injure', 'destroy'];
function followRules(action) {
return forbbidenActions.indexOf(action) < 0;
}
return {
execute: function (action, target) {
if (followRules(action)) {
console.log("I'll " + action + " " + target);
} else {
throw new Error("Must follow the Three Laws!");
}
}
}
})();
Example
var BasicMath = {
add: function (a, b) {
return a + b;
},
sub: function (a, b) {
return a - b;
}
};
window.BasicMath = BasicMath;
ExampleAsynchronous Module Definition
// Module Definition
define('BasicMath', [], function () {
return {
add: function (a, b) {
return a + b;
},
sub: function (a, b) {
return a - b;
}
}
});
// Module Consumption
require(['BasicMath'], function (BasicMath) {
console.log(BasicMath.add(2,4));
});
Example// Definition
var BasicMath = {
add: function (a, b) {
return a + b;
},
sub: function (a, b) {
return a - b;
}
};
module.exports = BasicMath;
// Consumption
var BasicMath = require('basicmath');
BasicMath.add(3, 4); // return 7 :p
define(function (require, exports, module) {
var validate = require('lib/validate');
exports.add = function (a, b) {
if (!validate(a) && !validate(b)) {
throw new Error('Must be real numbers');
}
return a + b;
};
exports.sub = function (a, b) {
return a - b;
};
});
(function (define) {
// AMD Style
define('BasicMath', function (require, exports) {
var validate = require('validate');
exports.add = function (a, b) {
if (!validate(a) && !validate(b)) {
throw new Error('Must be real numbers');
}
return a + b;
};
});
}(typeof define === 'function' && define.amd ? define : function (id, factory) {
if (typeof exports !== 'undefined') {
// It's CommonJS
factory(require, exports);
} else {
// Add Global
factory(function(value) {
return window[value];
}, (window[id] = {}));
}
}));
// Define (named)
var add = function (a, b) {/../}
var sub = function (a, b) {/../}
export { add, sub }
// Default
var BasicMath = { add: function (a, b) {/../}, sub: function(a,b ) {/../} }
export default BasicMath
// Use (named)
import { add, sub } from "basicmath"
// Use (default)
import BasicMath from "basicmath"