architecting javascript code
Post on 12-Nov-2014
944 Views
Preview:
DESCRIPTION
TRANSCRIPT
Architecting JavaScript Code
Suresh BallaPrincipal ConsultantNeudesic
Why do we need JavaScript patterns• Function Spaghetti Code• Closures to the Rescue
• Patterns• Prototype, Module
• Architecting Large JavaScript Codebases• Require.JS
Agenda
Why do we need JavaScript patterns?
Function Spaghetti Code
Problems with Function Spaghetti Code• Variables/functions added into global scope• Potential for duplicate function names• Not modular• Not easy to maintain• No sense of a “container”
Closures to the Rescue
What is a Closure?
“…an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.”
~ Douglas Crockford
Non-Closure Example
function myNonClosure() { var date = new Date(); return date.getMilliseconds();
}
Variable lost after function returns
Closure Example
function myClosure() { var date = new Date();
//nested function return function () {
return date.getMilliseconds(); };
}
Variable stays around even after function returns
Prototype Pattern
The Prototype Pattern• Pros: • Leverage JavaScript’s built-in features • “Modularize” code into re-useable objects • Variables/functions taken out of global namespace • Functions loaded into memory once • Possible to “override” functions through prototyping
• Cons: • “this” can be tricky • Constructor separate from prototype definition
Prototype Pattern Structure
var Calculator = function(eq) {this.eqCtl = document.getElementById(eq);
};
Calculator.prototype = {add: function (x, y) {
var val = x + y;this.eqCtl.innerHTML = val;
}}
var calc = new Calculator('eqCtl');calc.add(2,2)
Prototype Pattern Demo
The Module Pattern
The Module Pattern• Pros: • “Modularize” code into re-useable objects • Variables/functions taken out of global namespace • Expose only public members while hiding private
members
• Cons: • Functions may be duplicated across objects in memory
when not using singleton • Not easy to extend
Module Structure Overview
var Calculator = function() {//private variables //private functions
return {//public members
};};
Module Pattern Structure var Calculator = function(eq) {
//private membervar eqCtl = document.getElementById(eq);
return { //expose public member add: function(x,y) {
var val = x + y;eqCtl.innerHTML = val; }
};};
var calculator = new Calculator('eq');calculator.add(2,2)
Module Pattern Structure Demo
Architecting Large JavaScript Codebases• In C#, Assembly is Package
• JavaScript Feels Like File Based• Two Real Options• Build for Coexistence• Require.js
Architecting Large JavaScript CodebasesIsolating Scripts with Namespaces
<html> ...
<script source="first.js"></script> <script source="second.js"></script>
</html>
// first.js (function(ns) {
ns.Customer = function() { this.name = "";
}; }(window.WilderMinds = window.WilderMinds || {}));
// second.js (function(ns) {
ns.Order = function() { ... }; }(window.WilderMinds = window.WilderMinds || {}));
Architecting Large JavaScript Codebases • Require.js • http://requirejs.org/ • Uses the Asynchronous Module Definition (AMD) pattern • Dependency Injection for JavaScript • Loads Scripts as they are needed instead of all at start
Architecting Large JavaScript Codebases• Require.js • Include the Script • Add attribute for the startup script
<!DOCTYPE html> <html lang="en"> <head>
<meta charset="utf-8"> <title>RequireJS</title>
</head><body>
<script src="scripts/require.js" data-main="scripts/lib/main.js"> </script> </body></html>
Architecting Large JavaScript Codebases• Require.js• Main Script is executed on startup
// main.js require(["Customer"],
// Requires the Customer Module function (Customer) { // Call with required
Module(s) // Your Initialization Code var c = new Customer("A Customer"); var name = c.name;
} );
Architecting Large JavaScript Codebases• Require.js• Module Defined in similar way with define()
// Customer.js define( [], // Required Scripts (None)
function(){ // Gets any required modules here like main function Customer (name) {
this.name = name } return Customer; // Return the object that
Requires //constructor to allow you to call it }
Require.JS Demo
Q&A
top related