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

What's hot (20)

PPTX
Introduction to Spring Boot
Purbarun Chakrabarti
 
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
PPTX
React-JS Component Life-cycle Methods
ANKUSH CHAVAN
 
PDF
Introduction to Spring's Dependency Injection
Richard Paul
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPTX
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
PPTX
Java swing
Apurbo Datta
 
PDF
Object-oriented Programming-with C#
Doncho Minkov
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PPTX
Spring boot Introduction
Jeevesh Pandey
 
PPTX
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
PDF
An introduction to React.js
Emanuele DelBono
 
PPT
JAVA Polymorphism
Mahi Mca
 
PPTX
Dependency injection presentation
Ahasanul Kalam Akib
 
PPTX
React render props
Saikat Samanta
 
PPTX
This keyword in java
Hitesh Kumar
 
PPSX
JDBC: java DataBase connectivity
Tanmoy Barman
 
PPTX
OOPs in Java
Ranjith Sekar
 
PPTX
Hibernate ppt
Aneega
 
PPT
Java awt
Arati Gadgil
 
Introduction to Spring Boot
Purbarun Chakrabarti
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
React-JS Component Life-cycle Methods
ANKUSH CHAVAN
 
Introduction to Spring's Dependency Injection
Richard Paul
 
Exception Handling in JAVA
SURIT DATTA
 
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
Java swing
Apurbo Datta
 
Object-oriented Programming-with C#
Doncho Minkov
 
React + Redux Introduction
Nikolaus Graf
 
Spring boot Introduction
Jeevesh Pandey
 
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
An introduction to React.js
Emanuele DelBono
 
JAVA Polymorphism
Mahi Mca
 
Dependency injection presentation
Ahasanul Kalam Akib
 
React render props
Saikat Samanta
 
This keyword in java
Hitesh Kumar
 
JDBC: java DataBase connectivity
Tanmoy Barman
 
OOPs in Java
Ranjith Sekar
 
Hibernate ppt
Aneega
 
Java awt
Arati Gadgil
 

Viewers also liked (20)

PDF
JavaScript Patterns
Stoyan Stefanov
 
PDF
Scalable JavaScript Design Patterns
Addy Osmani
 
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
 
JavaScript Patterns
Stoyan Stefanov
 
Scalable JavaScript Design Patterns
Addy Osmani
 
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
 
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
 
Ad

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
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 

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>