4 JavaScript Design Patterns You Should Know (+ Scotchmas Day 2) - Scotch
4 JavaScript Design Patterns You Should Know (+ Scotchmas Day 2) - Scotch
(/)
4 JavaScript Design
Patterns You Should
Know (+ Scotchmas
Day 2)
Devan Patel ( (https://scotch.io/author/devan)@devanp92 (https://twitter.com/devanp92))
December 15, 2015
54
javascript
(https://scotch.io/tag/javascript)
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
shares
1/40
12/20/2015
POPULAR ON SCOT
Creating Deskto
write maintainable,
Applications Wi
Electron
AngularJS and G
(https://scotch.io/tutorials/cr
desktop-applications-with-an
as applications become
and-github-electron)
Create a MEAN
Google Map Ap
(https://scotch.io/tutorials/m
an organization structure
mean-apps-with-google-map
Containerized T
Node Applicatio
Dockunit
particular circumstance.
(https://scotch.io/tutorials/co
testing-for-node-applications
dockunit)
Aesthetic Sass 3
Typography and
Rhythm
(https://scotch.io/tutorials/ae
sass-3-typography-and-vertic
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
2/40
12/20/2015
Create a Custom
Polymer
Player Element
in certain circumstances,
(https://scotch.io/tutorials/cr
custom-audio-player-elemen
polymer)
Create a Real-T
Shoutbox with
others.
Events
(https://scotch.io/tutorials/cr
real-time-shoutbox-with-lara
Simbla: A Next
Responsive We
Builder
improve your
(https://scotch.io/tutorials/sim
programming repertoire
next-generation-responsive-w
builder)
JavaScript internals.
The design patterns in
question include the
following:
Module
Prototype
Observer
Singleton
Each pattern consists of
many properties.
However, I will emphasize
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
3/40
12/20/2015
(http://bit.ly/1FxJ
A VAGRANT LAMP S
THAT JUST WORK
like?
Module Design
Pattern
JavaScript modules are the
most prevalently used
design patterns for
keeping particular pieces
of code independent of
other components. This
(http://bit.ly/1PY0
DEAD SIMPLE
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
4/40PAN
OFF-CANVAS
12/20/2015
OFF-CANVAS PAN
support well-structured
code.
For those that are familiar
with object-oriented
languages, modules are
JavaScript classes. One of
the many advantages of
classes is encapsulation
protecting states and
behaviors from being
accessed from other
classes. The module
pattern allows for public
and private (plus the
(http://bit.ly/1QJL
SCOTCH.IO STICKE
(http://shop.scotc
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
5/40
12/20/2015
(function() {
// declare private variables and/or functions
return {
// declare public variables and/or functions
}
})();
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
6/40
12/20/2015
Notice that
callChangeHTML binds to
Revealing Module
Pattern
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
7/40
12/20/2015
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
8/40
12/20/2015
Exposer.first();
// Output: This is a method I want to ex
Exposer.second();
// Output: Inside a private method!
Exposer.methodToExpose; // undefined
9/40
12/20/2015
Prototype
Design Pattern
Any JavaScript developer
has either seen the
keyword prototype,
confused by the
prototypical inheritance or
implemented prototypes
in their code. The
Prototype design pattern
relies on the JavaScript
prototypical inheritance
(https://developer.mozilla.
org/enUS/docs/Web/JavaScript/In
heritance_and_the_prototy
pe_chain). The prototype
model is used mainly for
creating objects in
performance-intensive
situations.
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
10/40
12/20/2015
OUTLINE
pattern is performing an
extensive database
operation to create an
object used for other parts
of the application. If
another process needs to
use this object, instead of
having to perform this
substantial database
operation, it would be
advantageous to clone the
previously created object.
interface
Client
Prototype
import
operation()
clone()
Objectp=prototype.clone()
ConcretePrototype1
ConcretePrototype2
clone()
clone()
returncopyofself
returncopyofself
org/wikipedia/commons/1
Scroll /14/Prototype_UML.svg)
to Top
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
11/40
12/20/2015
= 'Model S';
}
TeslaModelS.prototype.go = function()
// Rotate wheels
}
TeslaModelS.prototype.stop = function(
// Apply brake pads
}
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
12/40
12/20/2015
= 'Model S';
}
TeslaModelS.prototype = {
go: function() {
// Rotate wheels
},
stop: function() {
// Apply brake pads
}
}
Revealing Prototype
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
13/40
12/20/2015
Revealing Prototype
Pattern
Similar to Module pattern,
the Prototype pattern also
has a revealing variation.
The Revealing Prototype
Pattern provides
encapsulation with public
and private members
since it returns an object
literal.
Since we are returning an
object, we will prefix the
prototype object with a
function. By extending
our example above, we
can choose what we want
to expose in the current
prototype to preserve
their access levels:
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
14/40
12/20/2015
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
15/40
12/20/2015
inheritance, there is no
need to rewrite underlying
features.
Observer Design
Pattern
There are many times
when one part of the
application changes, other
parts needs to be updated.
In AngularJS, if the $scope
object updates, an event
can be triggered to notify
another component. The
observer pattern
incorporates just that if
an object is modified it
broadcasts to dependent
objects that a change has
occurred.
Another prime example is
the model-view-controller
(MVC) architecture; The
view updates when the
model changes. One
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
16/40
12/20/2015
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
17/40
12/20/2015
// Controller 1
$scope.$on('nameChanged', function(event
$scope.name = args.name;
});
...
// Controller 2
$scope.userNameChanged = function(name
$scope.$emit('nameChanged', {name:
};
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
18/40
12/20/2015
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
19/40
12/20/2015
20/40
12/20/2015
Publish/Subscribe
The Publish/Subscribe
pattern, however, uses a
topic/event channel that
sits between the objects
wishing to receive
notifications (subscribers)
and the object firing the
event (the publisher). This
event system allows code
to define applicationspecific events that can
pass custom arguments
containing values needed
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
21/40
12/20/2015
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
22/40
12/20/2015
In AngularJS, a subscriber
subscribes to an event
using $on(event, callback),
and a publisher publishes
an event using
$emit(event, args) or
$broadcast(event, args).
Singleton
A Singleton only allows for
a single instantiation, but
many instances of the
same object. The Singleton
restricts clients from
creating multiple objects,
after the first object
created, it will return
instances of itself.
Finding use cases for
Singletons is difficult for
most who have not yet
used it prior. One example
is using an office printer. If
there are ten people in an
office, and they all use one
printer, ten computers
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
23/40
12/20/2015
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
24/40
12/20/2015
25/40
12/20/2015
In AngularJS, Singletons
are prevalent, the most
notable being services,
factories, and providers.
Since they maintain state
and provides resource
accessing, creating two
instances defeats the point
of a shared
service/factory/provider.
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
26/40
12/20/2015
Conclusion
Design patterns are
frequently used in larger
applications, though to
understand where one
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
27/40
12/20/2015
might be advantageous
over another, comes with
practice.
Before building any
application, you should
thoroughly think about
each actor and how they
interact with one another.
After reviewing the
Module, Prototype,
Observer, and Singleton
Scotchmas Day 2
Giveaway
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
28/40
12/20/2015
IT'S
OVER!
2,137
0/11
Scotchmug
Thiscontestisnolongeracceptingentries.
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
29/40
12/20/2015
(https://scotch.io/author/devan)
DEVAN PATEL
(HTTPS://SCOTCH.IO/AUTHOR/DEVAN)
(@DEVANP92
(HTTPS://TWITTER.COM/DEVANP92))
I'm an avid Javascript developer
which I write about here
(http://www.devanpatel.me). Feel
free to reach out to me on my
Twitter
(https://twitter.com/devanp92) or
check out the projects I work on
at my Github
(https://github.com/devanp92)!
View My Articles (https://scotch.io/author/devan)
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
30/40
12/20/2015
READ NEXT
(https://scotch.io/tutorials/building(https://scotch.io/baryour-own-
talk/s-o-l-i-d-
javascript-
the-first-five-
modal-
principles-of-
plugin)
object-
BUILDING
S.O.L.I.D:
YOUR OWN
THE FIRST 5
JAVASCRIPT
PRINCIPLES
MODAL
OF OBJECT
PLUGIN
ORIENTED
(HTTPS://SCOTCH.IO/TUTORIALS/BUILDINGDESIGN
YOUR-OWN(HTTPS://SCOTCH.IO/BARJAVASCRIPTTALK/S-O-LMODALI-D-THEPLUGIN)
FIRST-FIVEPRINCIPLESOF-OBJECTORIENTEDDESIGN)
(https://scotch.io/bar(https://scotch.io/bartalk/angular-
talk/changes-
material-vs-
and-reasons-
material-
behind-the-
design-lite)
new-scotch-
ANGULAR
CHANGES
MATERIAL
AND
VS.
REASONS
MATERIAL
BEHIND THE
DESIGN LITE
NEW
(HTTPS://SCOTCH.IO/BARSCOTCH.IO
TALK/ANGULARDESIGN
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
31/40
12/20/2015
MATERIALVSMATERIALDESIGNLITE)
(HTTPS://SCOTCH.IO/BARTALK/CHANGESANDREASONSBEHINDTHE-NEWSCOTCH-IO)
(https://scotch.io/bar(https://scotch.io/tutorials/googletalk/scotchmas-
material-
day-5-
design-input-
chromecast-
boxes-in-
jedi-bath-
css3)
SCOTCHMAS
GOOGLE
DAY 5
MATERIAL
CHROMECAST,
DESIGN
JEDI BATH
INPUT
ROBES, AND
BOXES IN
STAR WARS
CSS3
CODEPENS
(HTTPS://SCOTCH.IO/TUTORIALS/GOOGLE(HTTPS://SCOTCH.IO/BARMATERIALTALK/SCOTCHMASDESIGNDAY-5INPUTCHROMECASTBOXES-INJEDI-BATHCSS3)
ROBES-ANDSTAR-WARSCODEPENS)
MEAN MACHINE
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
32/40
12/20/2015
(https://leanpub.com/meanmachine)
Learn Node, Angular, Express,
and MongoDB from scratch.
No experience necessary.
Learn About the Book (https://leanpub.com/mean-machine)
SUBSCRIBE
FOLLOW LIKE
+1
(HTTPS://SCOTCH.IO/FEED)
(HTTP://TWITTER.COM/SCOTCH_IO)
(HTTP://WWW.FACEBOOK.COM/SCOTCHDEVELOP
(HTTP://PLUS.GOOGLE.COM/B/11385412
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
33/40
12/20/2015
Comments
Community
Recommend 5
Share
Login
SortbyBest
Jointhediscussion
skube 5daysago
Inyourveryfirstexampleyouhave:
return : {
// declare public variables and/or
}
Shouldn'ttherebenocolon?
2
Reply Share
DevanPatel>skube
8hoursago
HiSkube,
Firstoff,thanksforreadingthe
article.
Youarecorrectthereshouldnot
beacolon.Iwillreeditthepost.
Thankyou!
Reply Share
skube>DevanPatel
8hoursago
Np.Obviously,youknow
whatyouaredoingandit
wasasimpletypo.Ijustpoint
itoutforpeoplelikemewho
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
34/40
12/20/2015
itoutforpeoplelikemewho
easilygetconfused.
Reply Share
SergeyVoloshin 4daysago
JavaScript!It'llruntheworld!
1
Reply Share
gocreating adayago
Javascriptawesome!!
Reply Share
LeonidKolomiytsev 3daysago
Thanks,helpfulinformation)
Reply Share
TarunGarg 4daysago
Javascriptitsthenextbigthing...:D...
varmyFavLanguage="javascript"
Itwillruletheworld...x)
Reply Share
ChrisMathews 4daysago
Javascript,Python&R
Reply Share
Hisham 4daysago
Java&JS:))
Reply Share
Artsiom 4daysago
JavaScriptrulezzz!:))
Reply Share
AnastasiaSmirnova 4daysago
JSofcourse:)
Reply Share
M.Onurelik 4daysago
Javascript
Reply Share
MiguelLeite 4daysago
JavaScript:)
Reply Share
SerzN1 4daysago
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
35/40
12/20/2015
SerzN1 4daysago
"RevealingPrototypePattern"wrongcode
block!
Reply Share
MarcoGuglielmelli 4daysago
JavaScript!:)
Reply Share
YvesSchleich 4daysago
Agooddayhastostartwithscotch!
Reply Share
Mafisz 4daysago
PHP
Reply Share
Sarah 4daysago
AlwaysbetonJS)
Reply Share
mkdudeja 4daysago
document.getElementById("scotchmas
day2giveaway").innerHTML=
"JAVASCRIPT"
Reply Share
EltonVincent 4daysago
JSFTW!
Reply Share
RodrigoMoreno 4daysago
JavascriptFTW!
Reply Share
chadlefort 4daysago
JavaScript!
Reply Share
JD 4daysago
Javascript!!
Reply Share
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
36/40
12/20/2015
Reply Share
Rhadow 4daysago
JavaScript!
Reply Share
Yomi 4daysago
Javascriptbaby!
Reply Share
Matt 4daysago
Javascript!
Reply Share
TiagoWinehouse 4daysago
JS..NICE!!
Reply Share
ThibaultMaekelbergh 4daysago
Howistheprototypepatternevenrelevant
witheverythingES6gaveus?
Reply Share
morsaPT 4daysago
HeyDevan.Awesomearticle!
YouhaveanissueontheSingletonpattern
example.Youareusing`instance`on
getInstancemethodandthesameon
SingletonfunctionwhenIguessyoushould
beusing`printerInstance`.Canyoucheck?
Keepupwriting!:)
Reply Share
DevanPatel>morsaPT
8hoursago
HimorsaPT,
Thanksforthekindwords!
Kudostoyouforpointingitout!It
shouldbe'printerInstance'andnot
'instance'.
Reply Share
riozagreb 4daysago
jsftw
Reply Share
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
37/40
12/20/2015
Nick 4daysago
Javascriptforthewin!
Reply Share
DavorB. 4daysago
javascript
Reply Share
DjordjeAndzic 4daysago
Myfavoriteprogramminglanguageis
javascript.
Reply Share
NickGraz 4daysago
MyfavoritelanguageisPHP
Reply Share
SotirisKatsaniotis 5daysago
MyfavoriteprogramminglanguageisPHP
Reply Share
RizqyHidayat 5daysago
justgettingdeeperonjavascript.thanks!
Reply Share
Dill 5daysago
DefinitelyJavaScript
Reply Share
FleetNavTech 5daysago
AngularJS.
Reply Share
JonathanObino 5daysago
JSFTW!
Reply Share
NicoleLambon 5daysago
JavaScript,HTML,andCSSFTW!
Reply Share
AmirTugendhaft 5daysago
Python,theloveofmylife
Reply Share
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
38/40
12/20/2015
JairoJurado 5daysago
JavaScriptismyfavoritelanguage.Talk
aboutFrontandBackEnddevelopment
withonelanguage!
Reply Share
JustinSane 5daysago
ChooseJavascriptforsomuchWIN!
Reply Share
Cody 5daysago
JavaScriptiswhatIusemostbutIhaveto
sayIamenjoyingRubythemost.
Reply Share
5daysago
JS!
Reply Share
JohnH 5daysago
PHPismylanguageofchoice.
Reply Share
MarioGmez 5daysago
Myfavoriteprogramminglanguageis
JavaScript!
Reply Share
KostasKapenekakis 5daysago
Thanks!
Reply Share
RenanBorges 5daysago
License (/license)
Advertise with Us (/advertise)
About (/about)
Join Us on Slack (https://scotch-slack.herokuapp.com/)
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
39/40
12/20/2015
Store (http://shop.scotch.io)
Write for Us (/write-for-us)
Contact Us (/contact-us)
JOIN THE NEWSLETTER
Web design/development tutorials and news from around the web.
Email Address
Subscribe
Hire Us (http://bit.ly/18ib8jR)
(https://leanpub.com/mean-machine)
https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know
40/40