SlideShare a Scribd company logo
 
JavaScript Design Patterns. Subramanyan Murali Y! Geo team Bangalore Frontend Engineering Conference 2008
Coverage Introduction Pre-requisites  Module Pattern  Prototype Pattern Factory Pattern  Decorator Pattern Observer Pattern Yahoo! Internal presentation
Patterns?  General reusable solution to a commonly occurring problem in software design. Optimal solutions to common problems Yahoo! Internal presentation
Patterns? …  Description or template for how to solve a problem that can be used in many different situations Yahoo! Internal presentation
Patterns Creational Deal with class instantiation / Object Creation Structural Use inheritance to compose interfaces define ways to compose objects to obtain new functionality Behavioral concerned with communication between objects Yahoo! Internal presentation
JavaScript is not Java !@#$% Everything is an Object Class free Popular as a scripting language in the browser Typeless syntax No compilation  C-like syntax Late binding for all variables Yahoo! Internal presentation
Object Literal notation Yahoo! Internal presentation var  myObject =  {  name:  "Jack B. Nimble" , 'goto':  'Jail' , grade:  'A' , level: 3  } ; return { getData  : function( ) { return  private_data ; }, myVar   :  1 , my Str  :  “some String” ,   xtick   :  document.body.scrollLeft ,  ytick  :  document.body.scrollTop , };
Scope All properties and methods are in the public scope There is no  Block Scope Global Function No direct Static scope support Can provide properties & methods on constructors this  points to object that’s is calling a method Yahoo! Internal presentation
Global references Global variables are  Evil Non explicitly defined  vars  are implied global variables Less Global references = better JS code Yahoo! Internal presentation
Closure Inner function has access to the  vars  and parameters of the outer function vars  and parameters survive until reference to inner function survives Callbacks are good use-cases for using closures Example Yahoo! Internal presentation
Closure … Yahoo! Internal presentation function  createAdd  ( base ) { return   function ( num ) { return  base  +  num ;  // base is accessible through closure } } var  add5 = createAdd ( 5 ); alert (  add5 ( 2 )   );   // Alerts 7
Resembles classical Java like coding this  keyword is used to assign/access object properties and methods  No explicit return as all properties and methods are accessible on  this  Constructors create separate copies of members for each new object created Creational Pattern Constructors Yahoo! Internal presentation
Constructors … Yahoo! Internal presentation function  Car (  sColor ,  sMake  ) { this. color  =  sColor ; this. make  =  sMake ; this. showDetails  = function( ) { alert(this. color  + ” “ + this. make ); }; } var  myCar  = new  Car ( “Light Blue” ,  “Chevi Spark” ); Var  dadCar  = new  Car ( “Black” ,  “Honda City” );
Prototype Hidden link property If a item is accessed on an  object  is not present, then its is checked going up the  prototype chain Yahoo! Internal presentation var  test =  new  objC  ( ) test . initA  ( ); ObjB. prototype  = new ObjA ( ); ObjC. prototype  = new ObjB ( ); ObjA this. initA  ( ) ObjB this. initB  ( ) ObjC this. initC  ( )
Singletons Traditionally - Restrict instantiation of a class to one object In Javascript – The function object is pre-instantiated, and will have just one instance  Useful when exactly one object is needed to coordinate actions across the system Creational Pattern Yahoo! Internal presentation
Singletons … Yahoo! Internal presentation function  MyClass ( ) { if ( MyClass . caller  !=  MyClass . getInstance ) { throw new Error ( “MyClass is not a constructor" ); }  // this will ensure that users wont be able to do new MyClass()  var  myProperty  =  "hello world" ; this.myMethod  = function( ) { alert(  myProperty  ); }; } MyClass . _instance  = null;   //define the static property/flag MyClass . getInstance  = function ( ) { if (this.  _instance  == null) { this. _instance  = new  MyClass ( ); } return this. _instance ; } MyClass . getInstance ( ). myMethod ( );
Module Pattern Uses Singleton Paradigm Stays out of Global namespace Uses Object literal notation Supports private data Scales well for projects that becomes more complex and as its API grows Eric Miraglia’s  Explanation Yahoo! Internal presentation
Module Pattern … Yahoo! Internal presentation var  myModule  = function( ) {  var  _priVar  =  10 ;  // private attributes   var  _priMethod  = function( ) {   // private methods return  “foo” ;  };  return {  pubVar   :  10 ,  // public attributes  pubMethod  : function( ) {  // public methods return  “bar” ; }, getData  : function ( ) {  // Access private members return  _priMethod () + this. pubMethod ( ) + _priVar ;  } } } ( );   // get the anonymous function to execute and return myModule . getData ( );
Prototype Pattern Object type is determined by a prototypical instance No multiple copies of members Properties inside  constructor Methods on the  prototype Creational pattern Yahoo! Internal presentation
Prototype Pattern … Yahoo! Internal presentation function  myClassA ( ) { this. ppt1  =  10 ; this. ppt2  =  20 ; } myClassA .prototype. myMethod1  =  function( ) { return this. ppt1 ; } myClassA .prototype. myMethod2  = function( ) { return this. ppt2 ; } function  myClassB ( ) { this. ppt3  =  30 ; } myClassB .prototype = new  myClassA ( ); var  test  = new  myClassB ( ); alert (  test . ppt3  +  test . myMethod2 ( ) );
Prototype Pattern … Instance has just a reference to the methods defined on the prototype If code needs to establish inheritance, this is a good pattern to use Forms basis of  Lazy Inheritance postponed linking of an object with its prototype (class) until it is needed Yahoo! Internal presentation
Factory Pattern Main purpose is creation of objects Subclasses / Implementer decide which class to instantiate Useful to expose objects based on environment XHR objects on browsers Yahoo! Internal presentation
Factory Pattern … Yahoo! Internal presentation function  XMLHttpFactory ( )  {  this. createXMLHttp  = function( )  { if (typeof  XMLHttpRequest  !=  "undefined" )  { return new  XMLHttpRequest ( ); }  else if (typeof  window . ActiveXObject  !=  "undefined" )  { return new  ActiveXObject ( "MSXML2.XMLHttp" ); } else { alert (  “XHR Object not in production”  ); } }  var  xhr  =  XMLHttpFactory . createXMLHttp ( );
Factory Pattern …  Yahoo! Internal presentation function  shapeFactory ( ) { this. create  = function(  type ,  dimen  ) { switch ( type ) {  // dimension object { } case  "circle" : return { radius  :  dimen . radius ,  // pixel  getArea  : function ( ) { return (  22  /  7  ) * this. radius  * this. radius ; }  }; break; case  "square" :  return { length  :  dimen . length , breath  :  dimen . breath , getArea  : function ( ) { return this. length  * this. breath ; } }; break; } } }
Factory Pattern …  Yahoo! Internal presentation var  circle  = new  shapeFactory (). create ( "circle" , {  radius  :  5  }); circle . getArea ( ); var  square  = new  shapeFactory (). create ( "square" , {  length  :  10 ,  breath  :  20  }); square . getArea ( );
Decorator Pattern  Extend / decorate the functionality of a class at runtime Pass the original object as a parameter to the constructor of the decorator The decorator implements the new functionality Alternative to sub-classing Structural Pattern Yahoo! Internal presentation
Decorator Pattern … Yahoo! Internal presentation // Create a Name Space myText  = { }; myText . Decorators  = { }; // Core base class  myText . Core  = function(  myString  ) { this. show  = function( ) { return  myString ; }; } // First Decorator, to add question mark to string myText . Decorators . addQustionMark  = function (  myString  ) { this. show  = function( ){ return  myString . show ( ) +  '?' ; }; } //Second Decorator, to make string Italics myText . Decorators . makeItalic  = function(  myString  ) { this.show = function(){ return  &quot;<i>&quot;  +  myString . show ( ) +  &quot;</i>&quot; ; }; }
Decorator pattern Yahoo! Internal presentation //Third Decorator, to make first character of sentence caps myText . Decorators . upperCaseFirstChar  = function(  myString  ) { this. show  = function( ){ var  str  =  myString . show ( ); var  ucf  =  str . charAt ( 0 ). toUpperCase ( ); return  ucf  +  str . substr (  1 ,  str .length –  1  ); }; } // Set up the core String  var  theString  = new  myText . Core (  “this is a sample test string”  ); // Decorate the string with Decorators theString  = new  myText . Decorator . upperCaseFirstChar ( theString ); theString  = new  myText . Decorator . addQustionMark (  theString  ); theString  =  new myText. Decorator .makeItalic (  theString  );  theString . show ( );
Object changes state and all its observer objects are notified and updated automatically Also known as publisher/subscriber model Well demonstrated in modern event handling W3C’s  addEventListener Behavioral pattern Observer Pattern Yahoo! Internal presentation
Observer Pattern … Fits well for for applications that have lot of interactions Observer class must have the following Subject class also holds a private  list of observers Attach  method Detach  method Notify  method – to notify the change of state Yahoo! Internal presentation
Observer Pattern … Yahoo! Internal presentation // The Observer Object – One who super sees all the print operations  function  printManager ( ) { var  queue  = [ ]; // The attach method this. addJob  = function( name ,  job ) { queue . push ( {  ”name”  :  name ,  &quot;job”  :  job  } ); } // The detach method this. removeJob  = function( job ) { var  _queue  = [ ]; for(var  i  in  queue ) { if( queue [  i  ]. job  ==  job ) continue; else _queue . push (  queue [  i  ] ); } queue  =  _queue ; } …
Observer Pattern …  Yahoo! Internal presentation // The notify method this. doPrint  = function(  item  ) { for ( var  i  in  queue  ) { queue [  i  ]. job . call ( this,  item  ); } } } var  p  = new  printManager ();  // Publishers are in charge of &quot;publishing” function  printWithItalics (  str  ) {   // The callback function – the print job  alert(  “<i>”  +  str  +  “</i>”  ); } //Once subscribers are notified their callback functions are invoked] p. addJob (  &quot;italics&quot; ,  printWithItalics ); // Notify the observer about a state change p . doPrint ( &quot;this is a test&quot; );

More Related Content

PPTX
Builder design pattern
Salim Shadman Ankur
 
PPTX
Advanced JavaScript
Nascenia IT
 
PDF
Scalable JavaScript Application Architecture
Nicholas Zakas
 
PPT
Composite pattern
Shakil Ahmed
 
PPTX
Javascript Design Patterns
Iván Fernández Perea
 
PPTX
Angular 2
Nigam Goyal
 
PPT
Flyweight pattern
Shakil Ahmed
 
PDF
Exploiting Deserialization Vulnerabilities in Java
CODE WHITE GmbH
 
Builder design pattern
Salim Shadman Ankur
 
Advanced JavaScript
Nascenia IT
 
Scalable JavaScript Application Architecture
Nicholas Zakas
 
Composite pattern
Shakil Ahmed
 
Javascript Design Patterns
Iván Fernández Perea
 
Angular 2
Nigam Goyal
 
Flyweight pattern
Shakil Ahmed
 
Exploiting Deserialization Vulnerabilities in Java
CODE WHITE GmbH
 

What's hot (20)

PPSX
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
PDF
ES6 presentation
ritika1
 
PPT
Bridge Design Pattern
sahilrk911
 
PDF
Javascript essentials
Bedis ElAchèche
 
PPTX
Spring Web MVC
zeeshanhanif
 
PDF
Data Persistence in Android with Room Library
Reinvently
 
PDF
Introduction to Design Pattern
Sanae BEKKAR
 
PDF
Xpath in Selenium | Selenium Xpath Tutorial | Selenium Xpath Examples | Selen...
Edureka!
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Hacking Jenkins
Miro Cupak
 
PDF
Java Concurrency by Example
Ganesh Samarthyam
 
PPTX
Angular Data Binding
Jennifer Estrada
 
PDF
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
PPTX
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
PPT
Prototype pattern
Shakil Ahmed
 
PPTX
Design pattern-presentation
Rana Muhammad Asif
 
PDF
Scalable JavaScript Design Patterns
Addy Osmani
 
PPTX
Typescript in 30mins
Udaya Kumar
 
PDF
Black Hat EU 2010 - Attacking Java Serialized Communication
msaindane
 
PPT
Angular 8
Sunil OS
 
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
ES6 presentation
ritika1
 
Bridge Design Pattern
sahilrk911
 
Javascript essentials
Bedis ElAchèche
 
Spring Web MVC
zeeshanhanif
 
Data Persistence in Android with Room Library
Reinvently
 
Introduction to Design Pattern
Sanae BEKKAR
 
Xpath in Selenium | Selenium Xpath Tutorial | Selenium Xpath Examples | Selen...
Edureka!
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Hacking Jenkins
Miro Cupak
 
Java Concurrency by Example
Ganesh Samarthyam
 
Angular Data Binding
Jennifer Estrada
 
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
Prototype pattern
Shakil Ahmed
 
Design pattern-presentation
Rana Muhammad Asif
 
Scalable JavaScript Design Patterns
Addy Osmani
 
Typescript in 30mins
Udaya Kumar
 
Black Hat EU 2010 - Attacking Java Serialized Communication
msaindane
 
Angular 8
Sunil OS
 
Ad

Viewers also liked (20)

PDF
JavaScript Patterns
Stoyan Stefanov
 
KEY
JavaScript Growing Up
David Padbury
 
PDF
Javascript Module Patterns
Nicholas Jansma
 
PDF
Asynchronous Javascript and Rich Internet Aplications
Subramanyan Murali
 
PDF
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
PDF
The many facets of code reuse in JavaScript
Leonardo Borges
 
PPTX
Prototype design patterns
Thaichor Seng
 
PDF
Design Patterns : Solution to Software Design Problems
Edureka!
 
PPTX
Agile 101
beLithe
 
PDF
Basics of Rich Internet Applications
Subramanyan Murali
 
PDF
Large-Scale JavaScript Development
Addy Osmani
 
PPS
The Most Surprising Photos of 2014
guimera
 
PPTX
jQuery PPT
Dominic Arrojado
 
PPTX
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
Yahoo Developer Network
 
PDF
jQuery for beginners
Arulmurugan Rajaraman
 
PDF
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
PPTX
Efficient Android Threading
Anders Göransson
 
PDF
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
Yahoo Developer Network
 
PDF
Node Foundation Membership Overview 20160907
NodejsFoundation
 
PPT
Javascript
guest03a6e6
 
JavaScript Patterns
Stoyan Stefanov
 
JavaScript Growing Up
David Padbury
 
Javascript Module Patterns
Nicholas Jansma
 
Asynchronous Javascript and Rich Internet Aplications
Subramanyan Murali
 
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
The many facets of code reuse in JavaScript
Leonardo Borges
 
Prototype design patterns
Thaichor Seng
 
Design Patterns : Solution to Software Design Problems
Edureka!
 
Agile 101
beLithe
 
Basics of Rich Internet Applications
Subramanyan Murali
 
Large-Scale JavaScript Development
Addy Osmani
 
The Most Surprising Photos of 2014
guimera
 
jQuery PPT
Dominic Arrojado
 
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
Yahoo Developer Network
 
jQuery for beginners
Arulmurugan Rajaraman
 
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
Efficient Android Threading
Anders Göransson
 
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
Yahoo Developer Network
 
Node Foundation Membership Overview 20160907
NodejsFoundation
 
Javascript
guest03a6e6
 
Ad

Similar to Javascript Design Patterns (20)

PDF
Design patterns in javascript
Ayush Sharma
 
PPTX
Javascript Common Design Patterns
Pham Huy Tung
 
PPTX
Introduction to Design Patterns in Javascript
Santhosh Kumar Srinivasan
 
PPT
Javascript design patterns
GomathiNayagam S
 
PDF
Javascript Design Patterns
Lilia Sfaxi
 
PPTX
Design pattern in an expressive language java script
Amit Thakkar
 
PPT
Design pattern
Shreyance Jain
 
PPTX
JavaScript design patterns introduction
D Balaji
 
PDF
Design patterns in javascript
Abimbola Idowu
 
PPT
Java Script Patterns
Allan Huang
 
PPTX
Ajaxworld
deannalagason
 
PPTX
Js tips & tricks
Asia Tyshchenko
 
PDF
Introduction to JavaScript design patterns
Jeremy Duvall
 
KEY
Javascript tid-bits
David Atchley
 
PPTX
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
PPTX
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
FITC
 
PPTX
Framework prototype
DevMix
 
PPTX
Framework prototype
DevMix
 
PPTX
Framework prototype
DevMix
 
PDF
Unleashing the Power of Modern Javascript Development
Tarandeep Singh
 
Design patterns in javascript
Ayush Sharma
 
Javascript Common Design Patterns
Pham Huy Tung
 
Introduction to Design Patterns in Javascript
Santhosh Kumar Srinivasan
 
Javascript design patterns
GomathiNayagam S
 
Javascript Design Patterns
Lilia Sfaxi
 
Design pattern in an expressive language java script
Amit Thakkar
 
Design pattern
Shreyance Jain
 
JavaScript design patterns introduction
D Balaji
 
Design patterns in javascript
Abimbola Idowu
 
Java Script Patterns
Allan Huang
 
Ajaxworld
deannalagason
 
Js tips & tricks
Asia Tyshchenko
 
Introduction to JavaScript design patterns
Jeremy Duvall
 
Javascript tid-bits
David Atchley
 
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
FITC
 
Framework prototype
DevMix
 
Framework prototype
DevMix
 
Framework prototype
DevMix
 
Unleashing the Power of Modern Javascript Development
Tarandeep Singh
 

More from Subramanyan Murali (16)

PPTX
Yahoo Mail moving to React
Subramanyan Murali
 
PDF
Clipboard support on Y! mail
Subramanyan Murali
 
PDF
What the Hack??
Subramanyan Murali
 
PPTX
Web as a data resource
Subramanyan Murali
 
PPTX
Is it good to be paranoid ?
Subramanyan Murali
 
PPTX
When Why What of WWW
Subramanyan Murali
 
PPT
Welcome to University Hack Day @ IIT Chennai
Subramanyan Murali
 
PPTX
YUI for your Hacks
Subramanyan Murali
 
PPT
YUI open for all !
Subramanyan Murali
 
PPTX
Fixing the developer Mindset
Subramanyan Murali
 
PPT
Get me my data !
Subramanyan Murali
 
PDF
Professional Css
Subramanyan Murali
 
PPT
Yahoo! Frontend Building Blocks
Subramanyan Murali
 
PDF
Location aware Web Applications
Subramanyan Murali
 
PPT
YUI for your Hacks-IITB
Subramanyan Murali
 
PPT
Yahoo! Geo Technologies-IITD
Subramanyan Murali
 
Yahoo Mail moving to React
Subramanyan Murali
 
Clipboard support on Y! mail
Subramanyan Murali
 
What the Hack??
Subramanyan Murali
 
Web as a data resource
Subramanyan Murali
 
Is it good to be paranoid ?
Subramanyan Murali
 
When Why What of WWW
Subramanyan Murali
 
Welcome to University Hack Day @ IIT Chennai
Subramanyan Murali
 
YUI for your Hacks
Subramanyan Murali
 
YUI open for all !
Subramanyan Murali
 
Fixing the developer Mindset
Subramanyan Murali
 
Get me my data !
Subramanyan Murali
 
Professional Css
Subramanyan Murali
 
Yahoo! Frontend Building Blocks
Subramanyan Murali
 
Location aware Web Applications
Subramanyan Murali
 
YUI for your Hacks-IITB
Subramanyan Murali
 
Yahoo! Geo Technologies-IITD
Subramanyan Murali
 

Recently uploaded (20)

PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
This slide provides an overview Technology
mineshkharadi333
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 

Javascript Design Patterns

  • 1.  
  • 2. JavaScript Design Patterns. Subramanyan Murali Y! Geo team Bangalore Frontend Engineering Conference 2008
  • 3. Coverage Introduction Pre-requisites Module Pattern Prototype Pattern Factory Pattern Decorator Pattern Observer Pattern Yahoo! Internal presentation
  • 4. Patterns? General reusable solution to a commonly occurring problem in software design. Optimal solutions to common problems Yahoo! Internal presentation
  • 5. Patterns? … Description or template for how to solve a problem that can be used in many different situations Yahoo! Internal presentation
  • 6. Patterns Creational Deal with class instantiation / Object Creation Structural Use inheritance to compose interfaces define ways to compose objects to obtain new functionality Behavioral concerned with communication between objects Yahoo! Internal presentation
  • 7. JavaScript is not Java !@#$% Everything is an Object Class free Popular as a scripting language in the browser Typeless syntax No compilation C-like syntax Late binding for all variables Yahoo! Internal presentation
  • 8. Object Literal notation Yahoo! Internal presentation var myObject = { name: &quot;Jack B. Nimble&quot; , 'goto': 'Jail' , grade: 'A' , level: 3 } ; return { getData : function( ) { return private_data ; }, myVar : 1 , my Str : “some String” ,  xtick : document.body.scrollLeft , ytick : document.body.scrollTop , };
  • 9. Scope All properties and methods are in the public scope There is no Block Scope Global Function No direct Static scope support Can provide properties & methods on constructors this points to object that’s is calling a method Yahoo! Internal presentation
  • 10. Global references Global variables are Evil Non explicitly defined vars are implied global variables Less Global references = better JS code Yahoo! Internal presentation
  • 11. Closure Inner function has access to the vars and parameters of the outer function vars and parameters survive until reference to inner function survives Callbacks are good use-cases for using closures Example Yahoo! Internal presentation
  • 12. Closure … Yahoo! Internal presentation function createAdd ( base ) { return function ( num ) { return base + num ; // base is accessible through closure } } var add5 = createAdd ( 5 ); alert ( add5 ( 2 ) ); // Alerts 7
  • 13. Resembles classical Java like coding this keyword is used to assign/access object properties and methods No explicit return as all properties and methods are accessible on this Constructors create separate copies of members for each new object created Creational Pattern Constructors Yahoo! Internal presentation
  • 14. Constructors … Yahoo! Internal presentation function Car ( sColor , sMake ) { this. color = sColor ; this. make = sMake ; this. showDetails = function( ) { alert(this. color + ” “ + this. make ); }; } var myCar = new Car ( “Light Blue” , “Chevi Spark” ); Var dadCar = new Car ( “Black” , “Honda City” );
  • 15. Prototype Hidden link property If a item is accessed on an object is not present, then its is checked going up the prototype chain Yahoo! Internal presentation var test = new objC ( ) test . initA ( ); ObjB. prototype = new ObjA ( ); ObjC. prototype = new ObjB ( ); ObjA this. initA ( ) ObjB this. initB ( ) ObjC this. initC ( )
  • 16. Singletons Traditionally - Restrict instantiation of a class to one object In Javascript – The function object is pre-instantiated, and will have just one instance Useful when exactly one object is needed to coordinate actions across the system Creational Pattern Yahoo! Internal presentation
  • 17. Singletons … Yahoo! Internal presentation function MyClass ( ) { if ( MyClass . caller != MyClass . getInstance ) { throw new Error ( “MyClass is not a constructor&quot; ); } // this will ensure that users wont be able to do new MyClass() var myProperty = &quot;hello world&quot; ; this.myMethod = function( ) { alert( myProperty ); }; } MyClass . _instance = null; //define the static property/flag MyClass . getInstance = function ( ) { if (this. _instance == null) { this. _instance = new MyClass ( ); } return this. _instance ; } MyClass . getInstance ( ). myMethod ( );
  • 18. Module Pattern Uses Singleton Paradigm Stays out of Global namespace Uses Object literal notation Supports private data Scales well for projects that becomes more complex and as its API grows Eric Miraglia’s Explanation Yahoo! Internal presentation
  • 19. Module Pattern … Yahoo! Internal presentation var myModule = function( ) { var _priVar = 10 ; // private attributes var _priMethod = function( ) { // private methods return “foo” ; }; return { pubVar : 10 , // public attributes pubMethod : function( ) { // public methods return “bar” ; }, getData : function ( ) { // Access private members return _priMethod () + this. pubMethod ( ) + _priVar ; } } } ( ); // get the anonymous function to execute and return myModule . getData ( );
  • 20. Prototype Pattern Object type is determined by a prototypical instance No multiple copies of members Properties inside constructor Methods on the prototype Creational pattern Yahoo! Internal presentation
  • 21. Prototype Pattern … Yahoo! Internal presentation function myClassA ( ) { this. ppt1 = 10 ; this. ppt2 = 20 ; } myClassA .prototype. myMethod1 = function( ) { return this. ppt1 ; } myClassA .prototype. myMethod2 = function( ) { return this. ppt2 ; } function myClassB ( ) { this. ppt3 = 30 ; } myClassB .prototype = new myClassA ( ); var test = new myClassB ( ); alert ( test . ppt3 + test . myMethod2 ( ) );
  • 22. Prototype Pattern … Instance has just a reference to the methods defined on the prototype If code needs to establish inheritance, this is a good pattern to use Forms basis of Lazy Inheritance postponed linking of an object with its prototype (class) until it is needed Yahoo! Internal presentation
  • 23. Factory Pattern Main purpose is creation of objects Subclasses / Implementer decide which class to instantiate Useful to expose objects based on environment XHR objects on browsers Yahoo! Internal presentation
  • 24. Factory Pattern … Yahoo! Internal presentation function XMLHttpFactory ( ) { this. createXMLHttp = function( ) { if (typeof XMLHttpRequest != &quot;undefined&quot; ) { return new XMLHttpRequest ( ); } else if (typeof window . ActiveXObject != &quot;undefined&quot; ) { return new ActiveXObject ( &quot;MSXML2.XMLHttp&quot; ); } else { alert ( “XHR Object not in production” ); } } var xhr = XMLHttpFactory . createXMLHttp ( );
  • 25. Factory Pattern … Yahoo! Internal presentation function shapeFactory ( ) { this. create = function( type , dimen ) { switch ( type ) { // dimension object { } case &quot;circle&quot; : return { radius : dimen . radius , // pixel getArea : function ( ) { return ( 22 / 7 ) * this. radius * this. radius ; } }; break; case &quot;square&quot; : return { length : dimen . length , breath : dimen . breath , getArea : function ( ) { return this. length * this. breath ; } }; break; } } }
  • 26. Factory Pattern … Yahoo! Internal presentation var circle = new shapeFactory (). create ( &quot;circle&quot; , { radius : 5 }); circle . getArea ( ); var square = new shapeFactory (). create ( &quot;square&quot; , { length : 10 , breath : 20 }); square . getArea ( );
  • 27. Decorator Pattern Extend / decorate the functionality of a class at runtime Pass the original object as a parameter to the constructor of the decorator The decorator implements the new functionality Alternative to sub-classing Structural Pattern Yahoo! Internal presentation
  • 28. Decorator Pattern … Yahoo! Internal presentation // Create a Name Space myText = { }; myText . Decorators = { }; // Core base class myText . Core = function( myString ) { this. show = function( ) { return myString ; }; } // First Decorator, to add question mark to string myText . Decorators . addQustionMark = function ( myString ) { this. show = function( ){ return myString . show ( ) + '?' ; }; } //Second Decorator, to make string Italics myText . Decorators . makeItalic = function( myString ) { this.show = function(){ return &quot;<i>&quot; + myString . show ( ) + &quot;</i>&quot; ; }; }
  • 29. Decorator pattern Yahoo! Internal presentation //Third Decorator, to make first character of sentence caps myText . Decorators . upperCaseFirstChar = function( myString ) { this. show = function( ){ var str = myString . show ( ); var ucf = str . charAt ( 0 ). toUpperCase ( ); return ucf + str . substr ( 1 , str .length – 1 ); }; } // Set up the core String var theString = new myText . Core ( “this is a sample test string” ); // Decorate the string with Decorators theString = new myText . Decorator . upperCaseFirstChar ( theString ); theString = new myText . Decorator . addQustionMark ( theString ); theString = new myText. Decorator .makeItalic ( theString ); theString . show ( );
  • 30. Object changes state and all its observer objects are notified and updated automatically Also known as publisher/subscriber model Well demonstrated in modern event handling W3C’s addEventListener Behavioral pattern Observer Pattern Yahoo! Internal presentation
  • 31. Observer Pattern … Fits well for for applications that have lot of interactions Observer class must have the following Subject class also holds a private list of observers Attach method Detach method Notify method – to notify the change of state Yahoo! Internal presentation
  • 32. Observer Pattern … Yahoo! Internal presentation // The Observer Object – One who super sees all the print operations function printManager ( ) { var queue = [ ]; // The attach method this. addJob = function( name , job ) { queue . push ( { ”name” : name , &quot;job” : job } ); } // The detach method this. removeJob = function( job ) { var _queue = [ ]; for(var i in queue ) { if( queue [ i ]. job == job ) continue; else _queue . push ( queue [ i ] ); } queue = _queue ; } …
  • 33. Observer Pattern … Yahoo! Internal presentation // The notify method this. doPrint = function( item ) { for ( var i in queue ) { queue [ i ]. job . call ( this, item ); } } } var p = new printManager (); // Publishers are in charge of &quot;publishing” function printWithItalics ( str ) { // The callback function – the print job alert( “<i>” + str + “</i>” ); } //Once subscribers are notified their callback functions are invoked] p. addJob ( &quot;italics&quot; , printWithItalics ); // Notify the observer about a state change p . doPrint ( &quot;this is a test&quot; );
  • 34. Go see patterns  Thank you Yahoo! Internal presentation

Editor's Notes

  • #4: Creational patterns* Abstract Factory groups object factories that have a common theme.* Builder constructs complex objects by separating construction and representation.* Factory Method creates objects without specifying the exact class to create.* Prototype creates objects by cloning an existing object.* Singleton restricts object creation for a class to only one instance.Structural patterns* Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.* Bridge decouples an abstraction from its implementation so that the two can vary independently.* Composite composes one-or-more similar objects so that they can be manipulated as one object.* Decorator dynamically adds/overrides behaviour in an existing method of an object.* Facade provides a simplified interface to a large body of code.* Flyweight reduces the cost of creating and manipulating a large number of similar objects.* Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.Behavioral patterns* Chain of responsibility delegates commands to a chain of processing objects.* Command creates objects which encapsulate actions and parameters.* Interpreter implements a specialized language.* Iterator accesses the elements of an object sequentially without exposing its underlying representation.* Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.* Memento provides the ability to restore an object to its previous state (undo).* Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.* State allows an object to alter its behavior when its internal state changes.* Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.* Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.* Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object.<number>
  • #7: CreationalThese patterns have to do with class instantiation. They can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation to get the job done.StructuralThese concern class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.BehavioralMost of these design patterns are specifically concerned with communication between objects.<number>
  • #9: <number>
  • #10: Functions can have static members because in JS functions are objects and objects can have properties Functions which are used to initialize objects are called constructors<number>
  • #13: <number>
  • #14: Functions which are used to initialize objects are called constructors<number>
  • #16: Function ObjA(){this.initA = function(){alert(\"A\");}}Function ObjB(){this.initB = function(){alert(\"B\");}}ObjB.prototype = new ObjA();function ObjC(){this.initC = function(){alert(\"C\");}}ObjC.prototype = new ObjB();Var test = new ObjC();Test.initA();<number>
  • #24: Useful in creating plug-in based architectures<number>
  • #28: As an example, consider a window in a windowing system. To allow scrolling of the window's contents, we may wish to add horizontal or vertical scrollbars to it, as appropriate. Assume windows are represented by instances of the Window class, and assume this class has no functionality for adding scrollbars. We could create a subclass ScrollingWindow that provides them, or we could create a ScrollingWindowDecorator that merely adds this functionality to existing Window objects. At this point, either solution would be fine.The decorating class must have the same interface as the original class.Alternative to sub-classingSub-classing = extend at compile time<number>
  • #30: // Create a Name SpacemyText = { };myText.Decorators = { };// Core base class myText.Core = function( myString ) {this.show = function( ) {return myString;};}// First Decorator, to add question mark to stringmyText.Decorators.addQustionMark = function ( myString ) {this.show = function( ){return myString.show( ) + '?';};}//Second Decorator, to make string ItalicsmyText.Decorators.makeItalic = function( myString ) {this.show = function(){return \"<i>\" + myString.show( ) + \"</i>\";};}myText.Decorators.upperCaseFirstChar = function(myString) {this.show = function(){var str = myString.show();var ucf = str.charAt(0).toUpperCase();return ucf + str.substr( 1, str.length - 1 );};}var theString = new myText.Core( \"this is a sample test string\" );theString = new myText.Decorators.upperCaseFirstChar( theString );theString = new myText.Decorators.addQustionMark( theString );theString = new myText.Decorators.makeItalic( theString ); theString.show( );<number>
  • #31: addEventListener which allow you to register multiple listeners, and notify each callback by firing one event.<number>
  • #33: function printManager(){var queue = [];this.addJob = function(des, job){queue.push({\"description\":des,\"job\":job});}this.removeJob = function(job){var _queue = [];for(var i in queue){if(queue[i].job == job)continue;else_queue.push(queue[i]);}queue = _queue;}this.doPrint = function(item){for(var i in queue){queue[i].job.call(this, item);}}this.getQueue = function(){var _queue = [];for(var i in queue){_queue.push(queue[i].description);}return _queue;}}function addItalics(string){alert(\"<i>\"+ string + \"</i>\");}function addSome(str){alert(\"tetete\"+str);}var p = new printManager();p.addJob(\"italics\", addItalics);p.addJob(\"some\", addSome);p.removeJob(addItalics);p.doPrint(\"this is a test\");p.getQueue();<number>
  • #34: <number>