SlideShare a Scribd company logo
Design patterns in javascript
Design patterns in javascript
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
Design patterns in javascript
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()
Design patterns in javascript
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
Design patterns in javascript
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
Design patterns in javascript
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()
Design patterns in javascript
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
Design patterns in javascript
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
Design patterns in javascript
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
Design patterns in javascript
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
Ad

Recommended

Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
Tomohiro Kumagai
 
Class ‘increment’
Class ‘increment’
Syed Zaid Irshad
 
Javascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
Javascript Design Patterns
Javascript Design Patterns
Zohar Arad
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
VTU DSA Lab Manual
VTU DSA Lab Manual
AkhilaaReddy
 
AnyObject – 自分が見落としていた、基本の話
AnyObject – 自分が見落としていた、基本の話
Tomohiro Kumagai
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
tolmasky
 
Java script object model
Java script object model
James Hsieh
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
AngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
Javascript Styles and some tips
Javascript Styles and some tips
Vítor Baptista
 
Php 5.6
Php 5.6
Federico Damián Lozada Mosto
 
Lecture05
Lecture05
elearning_portal
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
Angular 2 Architecture
Angular 2 Architecture
Eyal Vardi
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
Odoo
 
AngularJS Animations
AngularJS Animations
Eyal Vardi
 
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?
Rafal Ksiazek
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
Nicolas Embleton
 
Advanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles
 
Composition in JavaScript
Composition in JavaScript
Josh Mock
 
MFC Message Handling
MFC Message Handling
Janani Anbarasan
 
Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)
Tomohiro Kumagai
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
Yan Yankowski
 
Cocoa heads 09112017
Cocoa heads 09112017
Vincent Pradeilles
 
What's new in iOS9
What's new in iOS9
CocoaHeads France
 
Javascript tid-bits
Javascript tid-bits
David Atchley
 
Javascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 

More Related Content

What's hot (20)

Java script object model
Java script object model
James Hsieh
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
AngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
Javascript Styles and some tips
Javascript Styles and some tips
Vítor Baptista
 
Php 5.6
Php 5.6
Federico Damián Lozada Mosto
 
Lecture05
Lecture05
elearning_portal
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
Angular 2 Architecture
Angular 2 Architecture
Eyal Vardi
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
Odoo
 
AngularJS Animations
AngularJS Animations
Eyal Vardi
 
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?
Rafal Ksiazek
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
Nicolas Embleton
 
Advanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles
 
Composition in JavaScript
Composition in JavaScript
Josh Mock
 
MFC Message Handling
MFC Message Handling
Janani Anbarasan
 
Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)
Tomohiro Kumagai
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
Yan Yankowski
 
Cocoa heads 09112017
Cocoa heads 09112017
Vincent Pradeilles
 
What's new in iOS9
What's new in iOS9
CocoaHeads France
 
Java script object model
Java script object model
James Hsieh
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
AngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
Javascript Styles and some tips
Javascript Styles and some tips
Vítor Baptista
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
Angular 2 Architecture
Angular 2 Architecture
Eyal Vardi
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
Odoo
 
AngularJS Animations
AngularJS Animations
Eyal Vardi
 
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?
Rafal Ksiazek
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
Nicolas Embleton
 
Advanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles
 
Composition in JavaScript
Composition in JavaScript
Josh Mock
 
Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)
Tomohiro Kumagai
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
Yan Yankowski
 

Similar to Design patterns in javascript (20)

Javascript tid-bits
Javascript tid-bits
David Atchley
 
Javascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Say It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
JavaScript Abstraction
JavaScript Abstraction
☆ Milan Adamovsky ☆
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
JavaScript Core
JavaScript Core
François Sarradin
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Exciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
JavaScript: Patterns, Part 1
JavaScript: Patterns, Part 1
Chris Farrell
 
Js tips & tricks
Js tips & tricks
Asia Tyshchenko
 
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
FITC
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Object oriented javascript
Object oriented javascript
Shah Jalal
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
The Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
Js objects
Js objects
anubavam-techkt
 
Object Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Javascript coding-and-design-patterns
Javascript coding-and-design-patterns
Hernan Mammana
 
ECMAScript2015
ECMAScript2015
qmmr
 
JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Exciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
JavaScript: Patterns, Part 1
JavaScript: Patterns, Part 1
Chris Farrell
 
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
FITC
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Object oriented javascript
Object oriented javascript
Shah Jalal
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Object Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Javascript coding-and-design-patterns
Javascript coding-and-design-patterns
Hernan Mammana
 
ECMAScript2015
ECMAScript2015
qmmr
 
Ad

Recently uploaded (20)

Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Technologies
 
Best MLM Compensation Plans for Network Marketing Success in 2025
Best MLM Compensation Plans for Network Marketing Success in 2025
LETSCMS Pvt. Ltd.
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Technologies
 
Best MLM Compensation Plans for Network Marketing Success in 2025
Best MLM Compensation Plans for Network Marketing Success in 2025
LETSCMS Pvt. Ltd.
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
Ad

Design patterns in javascript

  • 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
  • 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()
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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