SlideShare a Scribd company logo
1 of 62
Download to read offline
3
“One of the most important aspects of writing maintainable code is
being able to notice the recurring themes in that code and optimize
them. This is an area where knowledge of design patterns can prove
invaluable.”
4
5
6
7
9
10
// a simple facade that masks the various browser-
specific methods
function addEvent( element, event, callback ) {
if( window.addEventListener ) {
element.addEventListener( event, callback, false );
} else if( document.attachEvent ) {
element.attachEvent( 'on' + event, callback );
} else {
element[ 'on' + event ] = callback;
}
}
11
12
13
var app = express()
$getJson()
15
16
// build the Subject base class
var Subject = ( function( window, undefined ) {
function Subject() {
this._list = [];
}
// this method will handle adding observers to the internal list
Subject.prototype.observe = function observeObject( obj ) {
console.log( 'added new observer' );
this._list.push( obj );
};
...
17
Subject.prototype.unobserve = function unobserveObject( obj ) {
for( var i = 0, len = this._list.length; i < len; i++ ) {
if( this._list[ i ] === obj ) {
this._list.splice( i, 1 );
console.log( 'removed existing observer' );
return true;
}
}
return false;
};
Subject.prototype.notify = function notifyObservers() {
var args = Array.prototype.slice.call( arguments, 0 );
for( var i = 0, len = this._list.length; i < len; i++ ) {
this._list[ i ].update.apply( null, args );
}
};
return Subject;
} )( window );
18
19
20
22
23
var mySingleton = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
var privateRandomNumber = Math.random();
return {
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
24
// Usage:
var A = mySingleton.getInstance();
var B = mySingleton.getInstance();
console.log(
A.getRandomNumber() === B.getRandomNumber()
); // true
25
26
27
29
30
// build our blueprint object
var MyBluePrint = function MyBluePrintObject() {
this.someFunction = function someFunction() {
alert( 'some function' );
};
this.showMyName = function showMyName() {
alert( this.name );
};
};
function MyObject() {
this.name = 'testing';
}
MyObject.prototype = new MyBluePrint();
31
32
Object.create()
34
35
var orgChart = {
addNewEmployee: function(){
// getEmployeeDetail provides a view that users interact with
var employeeDetail = this.getEmployeeDetail();
// when the employee detail is complete, the mediator (the 'orgchart' object)
// decides what should happen next
employeeDetail.on("complete", function(employee){
// set up additional objects that have additional events, which are used
// by the mediator to do additional things
var managerSelector = this.selectManager(employee);
managerSelector.on("save", function(employee){
employee.save();
});
});
},
// ...
}
36
37
39
40
41
function CarDoor( options ) {
this.color = options.color || 'red';
this.side = options.side || 'right';
this.hasPowerWindows = options.hasPowerWindows || true;
}
function CarSeat( options ) {
this.color = options.color || 'gray';
this.material = options.material || 'leather';
this.isReclinable = options.isReclinable || true;
}
42
function CarPartFactory() {}
CarPartFactory.prototype.createPart = function createCarPart( options ) {
var parentClass = null;
if( options.partType === 'door' ) {
parentClass = CarDoor;
} else if( options.partType === 'seat' ) {
parentClass = CarSeat;
}
if( parentClass === null ) {
return false;
}
return new parentClass( options );
}
43
// example usage
var myPartFactory = new CarPartFactory();
var seat = myPartFactory.createPart( {
partType : 'seat',
material : 'leather',
color : 'blue',
isReclinable : false
});
// outputs: true
console.log( seat instanceof CarSeat );
// outputs a CarSeat object with material "leather", color "blue",
isReclinable "false"
console.log( seat );
44
45
46
48
49
50
( function( window, undefined ) {
// normally variables & functions start with a lowercase letter but with modules, that is not the
case.
// The general tradition is to start them with a capital letter instead.
function MyModule() {
// `this` refers to the instance of `MyModule` when created
this.myMethod = function myMethod() {
alert( 'my method' );
};
// note that we still use a function declaration even when using a function expression.
// for more information on why, check out: http://kangax.github.io/nfe/
this.myOtherMethod = function myOtherMethod() {
alert( 'my other method' );
};
}
// expose access to the constructor
window.MyModule = MyModule;
} )( window );
51
// example usage
var myModule = new MyModule();
myModule.myMethod(); // alerts "my method"
myModule.myOtherMethod(); // alerts "my other method"
52
53
55
56
var myRevealingModule = (function () {
var privateVar = "Ben Cherry",
publicVar = "Hey there!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
function publicSetName( strName ) {
privateVar = strName;
}
function publicGetName() {
privateFunction();
}
// Reveal public pointers to
// private functions and properties
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
})();
myRevealingModule.setName( "Paul Kinlan" );
57
58
59
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
60
http://uml.org.cn/c++/pdf/DesignPatterns.pdf
61
62

More Related Content

What's hot

Java script object model
Java script object modelJava script object model
Java script object model
James Hsieh
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 

What's hot (20)

Java script object model
Java script object modelJava script object model
Java script object model
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 
Javascript Styles and some tips
Javascript Styles and some tipsJavascript Styles and some tips
Javascript Styles and some tips
 
Php 5.6
Php 5.6Php 5.6
Php 5.6
 
Lecture05
Lecture05Lecture05
Lecture05
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftSwift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
 
Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSGDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
MFC Message Handling
MFC Message HandlingMFC Message Handling
MFC Message Handling
 
Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
What's new in iOS9
What's new in iOS9What's new in iOS9
What's new in iOS9
 

Similar to Design patterns in javascript

JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Robert Nyman
 

Similar to Design patterns in javascript (20)

Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScript
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Day 1
Day 1Day 1
Day 1
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Wcbpijwbpij new
Wcbpijwbpij newWcbpijwbpij new
Wcbpijwbpij new
 

Recently uploaded

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Recently uploaded (20)

WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 

Design patterns in javascript

  • 1.
  • 2.
  • 3. 3 “One of the most important aspects of writing maintainable code is being able to notice the recurring themes in that code and optimize them. This is an area where knowledge of design patterns can prove invaluable.”
  • 4. 4
  • 5. 5
  • 6. 6
  • 7. 7
  • 8.
  • 9. 9
  • 10. 10 // a simple facade that masks the various browser- specific methods function addEvent( element, event, callback ) { if( window.addEventListener ) { element.addEventListener( event, callback, false ); } else if( document.attachEvent ) { element.attachEvent( 'on' + event, callback ); } else { element[ 'on' + event ] = callback; } }
  • 11. 11
  • 12. 12
  • 13. 13 var app = express() $getJson()
  • 14.
  • 15. 15
  • 16. 16 // build the Subject base class var Subject = ( function( window, undefined ) { function Subject() { this._list = []; } // this method will handle adding observers to the internal list Subject.prototype.observe = function observeObject( obj ) { console.log( 'added new observer' ); this._list.push( obj ); }; ...
  • 17. 17 Subject.prototype.unobserve = function unobserveObject( obj ) { for( var i = 0, len = this._list.length; i < len; i++ ) { if( this._list[ i ] === obj ) { this._list.splice( i, 1 ); console.log( 'removed existing observer' ); return true; } } return false; }; Subject.prototype.notify = function notifyObservers() { var args = Array.prototype.slice.call( arguments, 0 ); for( var i = 0, len = this._list.length; i < len; i++ ) { this._list[ i ].update.apply( null, args ); } }; return Subject; } )( window );
  • 18. 18
  • 19. 19
  • 20. 20
  • 21.
  • 22. 22
  • 23. 23 var mySingleton = (function () { // Instance stores a reference to the Singleton var instance; function init() { var privateRandomNumber = Math.random(); return { getRandomNumber: function() { return privateRandomNumber; } }; }; return { // Get the Singleton instance if one exists // or create one if it doesn't getInstance: function () { if ( !instance ) { instance = init(); } return instance; } }; })();
  • 24. 24 // Usage: var A = mySingleton.getInstance(); var B = mySingleton.getInstance(); console.log( A.getRandomNumber() === B.getRandomNumber() ); // true
  • 25. 25
  • 26. 26
  • 27. 27
  • 28.
  • 29. 29
  • 30. 30 // build our blueprint object var MyBluePrint = function MyBluePrintObject() { this.someFunction = function someFunction() { alert( 'some function' ); }; this.showMyName = function showMyName() { alert( this.name ); }; }; function MyObject() { this.name = 'testing'; } MyObject.prototype = new MyBluePrint();
  • 31. 31
  • 33.
  • 34. 34
  • 35. 35 var orgChart = { addNewEmployee: function(){ // getEmployeeDetail provides a view that users interact with var employeeDetail = this.getEmployeeDetail(); // when the employee detail is complete, the mediator (the 'orgchart' object) // decides what should happen next employeeDetail.on("complete", function(employee){ // set up additional objects that have additional events, which are used // by the mediator to do additional things var managerSelector = this.selectManager(employee); managerSelector.on("save", function(employee){ employee.save(); }); }); }, // ... }
  • 36. 36
  • 37. 37
  • 38.
  • 39. 39
  • 40. 40
  • 41. 41 function CarDoor( options ) { this.color = options.color || 'red'; this.side = options.side || 'right'; this.hasPowerWindows = options.hasPowerWindows || true; } function CarSeat( options ) { this.color = options.color || 'gray'; this.material = options.material || 'leather'; this.isReclinable = options.isReclinable || true; }
  • 42. 42 function CarPartFactory() {} CarPartFactory.prototype.createPart = function createCarPart( options ) { var parentClass = null; if( options.partType === 'door' ) { parentClass = CarDoor; } else if( options.partType === 'seat' ) { parentClass = CarSeat; } if( parentClass === null ) { return false; } return new parentClass( options ); }
  • 43. 43 // example usage var myPartFactory = new CarPartFactory(); var seat = myPartFactory.createPart( { partType : 'seat', material : 'leather', color : 'blue', isReclinable : false }); // outputs: true console.log( seat instanceof CarSeat ); // outputs a CarSeat object with material "leather", color "blue", isReclinable "false" console.log( seat );
  • 44. 44
  • 45. 45
  • 46. 46
  • 47.
  • 48. 48
  • 49. 49
  • 50. 50 ( function( window, undefined ) { // normally variables & functions start with a lowercase letter but with modules, that is not the case. // The general tradition is to start them with a capital letter instead. function MyModule() { // `this` refers to the instance of `MyModule` when created this.myMethod = function myMethod() { alert( 'my method' ); }; // note that we still use a function declaration even when using a function expression. // for more information on why, check out: http://kangax.github.io/nfe/ this.myOtherMethod = function myOtherMethod() { alert( 'my other method' ); }; } // expose access to the constructor window.MyModule = MyModule; } )( window );
  • 51. 51 // example usage var myModule = new MyModule(); myModule.myMethod(); // alerts "my method" myModule.myOtherMethod(); // alerts "my other method"
  • 52. 52
  • 53. 53
  • 54.
  • 55. 55
  • 56. 56 var myRevealingModule = (function () { var privateVar = "Ben Cherry", publicVar = "Hey there!"; function privateFunction() { console.log( "Name:" + privateVar ); } function publicSetName( strName ) { privateVar = strName; } function publicGetName() { privateFunction(); } // Reveal public pointers to // private functions and properties return { setName: publicSetName, greeting: publicVar, getName: publicGetName }; })(); myRevealingModule.setName( "Paul Kinlan" );
  • 57. 57
  • 58. 58
  • 61. 61
  • 62. 62