(Ebook) JavaScript Design Patterns by Hugo Di Francesco download
(Ebook) JavaScript Design Patterns by Hugo Di Francesco download
Francescoinstall download
https://ebooknice.com/product/javascript-design-patterns-56190208
https://ebooknice.com/product/mastering-javascript-design-patterns-create-
scalable-and-reliable-applications-with-advanced-javascript-design-patterns-
using-reliable-code-9992610
ebooknice.com
https://ebooknice.com/product/mastering-javascript-design-patterns-6724550
ebooknice.com
https://ebooknice.com/product/learning-javascript-design-patterns-56633862
ebooknice.com
https://ebooknice.com/product/learning-javascript-design-patterns-49002748
ebooknice.com
(Ebook) Learning JavaScript Design Patterns by Addy Osmani ISBN 9781449331818,
1449331815
https://ebooknice.com/product/learning-javascript-design-patterns-2561268
ebooknice.com
(Ebook) JavaScript Patterns: Build Better Applications with Coding and Design
Patterns by Stefanov, Stoyan ISBN 9780596806750, 0596806752
https://ebooknice.com/product/javascript-patterns-build-better-applications-
with-coding-and-design-patterns-55886614
ebooknice.com
(Ebook) Pro JavaScript Design Patterns by Ross Harmes; Dustin Diaz ISBN
9781590599082, 159059908X
https://ebooknice.com/product/pro-javascript-design-patterns-34822960
ebooknice.com
(Ebook) Learning JavaScript Design Patterns, 2nd Edition by Addy Osmani ISBN
9781098139865, 1098139860
https://ebooknice.com/product/learning-javascript-design-patterns-2nd-
edition-47549710
ebooknice.com
(Ebook) Pro Javascript Design Patterns by Ross Harmes, Dustin Diaz ISBN
9781590599082, 9781430204954, 159059908X, 1430204958
https://ebooknice.com/product/pro-javascript-design-patterns-43150420
ebooknice.com
JavaScript Design Patterns
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express or
implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for
any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-80461-227-9
www.packtpub.com
To my wife, Amalia, for being my first supporter in all my endeavors. To my daughter, Zoë, for
making me want to show that the impossible sometimes is.
– Hugo Di Francesco
Contributors
His journey is marked by successive achievements, particularly in handling core subjects and
programming languages, with a keen emphasis on practical knowledge. As a mentor and guide for
major projects, Dr. Murugavel actively engages in groundbreaking research within his specialized
field. His commitment to bridging theory and application has made him a valuable resource for
students and researchers alike.
His technical proficiency extends across a spectrum of disciplines. He is well-versed in full stack web
development, SQL, data analytics, Python, and BI tools, showcasing theoretical knowledge and a
hands-on understanding of these technologies. His extensive portfolio includes the development of
numerous applications using JSP, ASP, and ASP.NET, reflecting his prowess in both frontend and
backend development.
In the realm of databases, he demonstrates versatility across MS-SQL Server, MySQL, MongoDB,
Django, MS Access, Oracle, and FoxPro. His proficiency in various Integrated Development
Environments (IDEs) and tools such as Anaconda, Visual Studio, GitHub, JBuilder, JCreator,
MATLAB, Sublime 3, and Adobe Dreamweaver further solidifies his standing in the technological
landscape.
In the realm of data science and Business Intelligence (BI) tools, his skills are extensive,
encompassing PowerBI, DAX, VBA Macros for Excel, SSAS, and SSIS. His ability to harness these
tools illuminates the path to insightful data analysis and visualization.
Shubham Thakur, a dynamic senior software engineer (A3 grade) at EPAM, specializes in
technologies such as JavaScript, Angular, Next.js, Node, MySQL, MongoDB, AWS Cloud, and IoT.
His expertise in these domains has significantly contributed to his project successes. He expresses
deep gratitude to Priya for her unwavering love and to his brother, Yash, for his constant support.
Shubham also acknowledges the profound impact of his mentors, Avnish Aggarwal, Yogesh
Dhandekar, and Amit Jain, whose guidance has been instrumental in shaping his professional
journey. Their mentorship has not only honed his technical skills but also enriched his approach to
complex problem-solving in the tech industry.
Table of Contents
Preface
Part 1: Design Patterns
10
Index
Design patterns are solutions to common problems that can be reused. The most-written-about design
patterns come from the world of object-oriented programming.
There are many resources on JavaScript and design patterns, but this book provides a cohesive and
comprehensive view of design patterns in modern (ECMAScript 6+) JavaScript with real-world
examples of how to deploy them in a professional setting. In addition to this complete library of
patterns to apply to projects, this book also provides an overview of how to structure different parts
of an application to deliver high performance at scale.
In this book, you will be provided with up-to-date guidance through the world of modern JavaScript
patterns based on nine years of experience building and deploying JavaScript and React applications
at scale at companies such as Elsevier, Canon, and Eurostar, delivering multiple system evolutions,
performance projects, and a next-generation frontend application architecture.
Who this book is for
This book is for developers and software architects who want to leverage JavaScript and the web
platform to increase productivity, software quality, and the performance of their applications.
Familiarity with software design patterns would be a plus but is not required.
The three main challenges faced by developers and architects who are the target audience of this
content are as follows:
They are familiar with programming concepts but not how to effectively implement them in JavaScript
They want to structure JavaScript code and applications in a way that is maintainable and extensible
They want to deliver more performance to the users of their JavaScript applications
What this book covers
Chapter 1, Working with Creational Design Patterns, covers creational design patterns, which help to
organize object creation. We’ll look at implementing the prototype, singleton, and factory patterns in
JavaScript.
Chapter 2, Implementing Structural Design Patterns, looks at structural design patterns, which help
to organize relationships between entities. We’ll implement the proxy, decorator, flyweight, and
adapter patterns in JavaScript.
Chapter 3, Leveraging Behavioral Design Patterns, delves into behavioral design patterns, which
help to organize communication between objects. We’ll learn about the observer, state, strategy, and
visitor patterns in JavaScript.
Chapter 4, Exploring Reactive View Library Patterns, explores reactive view libraries, such as React,
which have taken over the JavaScript application landscape. With these libraries come new patterns
to explore, implement, and contrast.
Chapter 5, Rendering Strategies and Page Hydration, takes a look at optimizing page performance,
which is a key concern nowadays. It’s a concern both for improving the on-page conversion of
customers and search engine optimization, since search engines such as Google take core web vitals
into account.
Chapter 6, Micro Frontends, Zones, and Islands Architectures, explores micro frontends. Akin to the
microservices movement in the service tier, micro frontends are designed to split a large surface area
into smaller chunks that can be worked on and delivered at higher velocity.
Chapter 9, Maximizing Performance – Lazy Loading and Code Splitting, deals with how, in order to
maximize the performance of a JavaScript application, reducing the amount of unused JavaScript
being loaded and interpreted is key. The techniques that can be brought to bear on this problem are
called lazy loading and code splitting.
Chapter 10, Asset-Loading Strategies and Executing Code off the Main Thread, looks at how there
are situations in the lifecycle of an application where loading more JavaScript or assets is inevitable.
You will learn about asset-loading optimizations in the specific case of JavaScript, as well as other
web resources, and finally how to execute JavaScript off the main browser thread.
If you are using the digital version of this book, we advise you to type the code yourself or
access the code from the book’s GitHub repository (a link is available in the next section).
Doing so will help you avoid any potential errors related to the copying and pasting of code.
We also have other code bundles from our rich catalog of books and videos available at
https://github.com/PacktPublishing/. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “ In order
to make the code easier to follow, we’ll switch on the lowercased version of tagName.”
<script>
// handle receiving messages from iframe -> parent
const allowedMessageOrigins = ['http://127.0.0.1:8000'];
window.addEventListener('message', (event) => {
if (!allowedMessageOrigins.includes(event.origin)) {
console.warn(
`Dropping message due to non-allowlisted origin ${event.origin}`,
event,
);
return;
}
// no change to the rest of the message handler
});
</script>
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words
in menus or dialog boxes appear in bold. Here is an example: “When opening the select, things seem
to work ok, we’re seeing the Fruit: prefix for all the options.”
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at
[email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you have found a mistake in this book, we would be grateful if you would report this to us.
Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be
grateful if you would provide us with the location address or website name. Please contact us at
[email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you
are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Your review is important to us and the tech community and will help us make sure we’re delivering
excellent quality content.
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical
books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free
content in your inbox daily
https://packt.link/free-ebook/978-1-80461-227-9
3. That’s it! We’ll send your free PDF and other benefits to your email directly
Part 1:Design Patterns
In this part, you will get an overview of design patterns and how they can be implemented effectively
in modern JavaScript. You will learn how and when to implement creational, structural, and
behavioral design patterns in the “classical” object-oriented way and how modern JavaScript features
can be used to make this implementation more idiomatic to the language. Finally, you’ll see real-
world examples of design patterns being applied in the JavaScript ecosystem, thereby learning how to
recognize them.
Creational design patterns give structure to object creation, which enables the development of
systems and applications where different modules, classes, and objects don’t need to know how to
create instances of each other. The design patterns most relevant to JavaScript – the prototype,
singleton, and factory patterns – will be explored, as well as situations where they’re helpful and how
to implement them in an idiomatic fashion.
An implementation of the singleton design pattern, eager and lazy initialization, use cases for singleton, and what a singleton
pattern in modern JavaScript looks like
How to implement the factory pattern using classes, a modern JavaScript alternative, and use cases
By the end of this chapter, you’ll be able to identify when a creational design pattern is useful and
make an informed decision on which of its multiple implementations to use, ranging from a more
idiomatic JavaScript form to a classical form.
In fact, modern idiomatic JavaScript tends to lean more toward procedural and function paradigms
than object orientation. This means that creational design patterns may have to be adapted to be fully
useful in JavaScript.
In summary, creational design patterns are useful in object-oriented JavaScript, since they hide
instantiation details from consumers, which keeps coupling low, thereby allowing better module
separation.
In the next section, we’ll encounter our first creational design pattern – the prototype design pattern.
The prototype design pattern allows us to create an instance based on another existing instance (our
prototype).
In more formal terms, a prototype class exposes a clone() method. Consuming code, instead of
calling new SomeClass, will call new SomeClassPrototype(someClassInstance).clone(). This method
call will return a new SomeClass instance with all the values copied from someClassInstance.
Implementation
Let’s imagine a scenario where we’re building a chessboard. There are two key types of squares –
white and black. In addition to this information, each square contains information such as its row,
file, and which piece sits atop it.
class BoardSquare {
constructor(color, row, file, startingPiece) {
this.color = color;
this.row = row;
this.file = file;
}
}
class BoardSquare {
// no change to the rest of the class
occupySquare(piece) {
this.piece = piece;
}
clearSquare() {
this.piece = null;
}
}
Note the repetition of arguments being passed to new BoardSquare, which will cause issues if we want
to change all board squares to black. We would need to change the parameter passed to each call of
BoardSquare is one by one for each new BoardSquare call. This can be quite error-prone; all it takes is
one hard-to-find mistake in the color value to cause a bug:
Implementing our instantiation logic using a classical prototype looks as follows. We need a
BoardSquarePrototype class; its constructor takes a prototype property, which it stores on the
instance. BoardSquarePrototype exposes a clone() method that takes no arguments and returns a
BoardSquare instance, with all the properties of prototype copied onto it:
class BoardSquarePrototype {
constructor(prototype) {
this.prototype = prototype;
}
clone() {
const boardSquare = new BoardSquare();
boardSquare.color = this.prototype.color;
boardSquare.row = this.prototype.row;
boardSquare.file = this.prototype.file;
return boardSquare;
}
}
2. We can then use whiteSquarePrototype with .clone() to create our copies of whiteSquare. Note that color is
copied over but each call to clone() returns a new instance.
Every ship is a romantic object, except that we sail in. Embark and
the romance quits our vessel, and hangs on every other sail in the
horizon.
Emerson (Essay on Experience).
The globe has been circumnavigated, but no man ever yet has;
you may survey a kingdom and note the result in maps, but all the
savants in the world could not produce a reliable map of the poorest
human personality. And the worst of all this is, that love and
friendship may be the outcome of a certain condition of knowledge;
increase the knowledge, and love and friendship beat their wings
and go. Every man’s road in life is marked by the graves of his
personal likings. Intimacy is frequently the road to indifference; and
marriage a parricide.
Alexander Smith (The Importance of a Man to Himself).
ISOLATION
Yes! in the sea of life enisled,
With echoing straits between us thrown,
Dotting the shoreless watery wild,
We mortal millions live alone.
The islands feel the enclasping flow,
And then their endless bounds they know.
Matthew Arnold.
This fine poem is one of a series called “Switzerland,” which was written as the
result of Arnold’s meeting and falling in love with a lady at Berne. The poem
immediately preceding it in the series is entitled “Isolation: To Marguerite,” while
this is called “To Marguerite, Continued” but as it is now quoted separately, it is
better entitled “Isolation.”
In the preceding poems the lady has lost her affection while her lover is still
devoted; and this leads to the subject of our isolation from each other in our inner
lives. In the second verse the poet describes the moments when we most crave
for love, sympathy, and mutual spiritual understanding and union.
For an interesting fact connected with this poem, see next quotation and note.
The similarity between this passage and the preceding poem, written at about
the same time, is very curious. Arnold’s poem appeared in 1852 but was
composed ten years earlier, while Pendennis was published in monthly parts in
1849-50. Therefore, neither author would consciously know at the time what the
other had written.
The incident is probably an illustration of the mysterious way in which minds
influence one another and create the spirit of the particular age. There is, I
believe, a Chinese proverb to the effect that we are more the product of our age
than of our parents. This permeating quality of thought and feeling is, no doubt,
the explanation why the highest art and literature, though often unappreciated at
the time, become ultimately recognized. It appears not to be sufficiently taken into
account in other directions. For instance, it is repeatedly stated that Blake,
because of the limited circulation of his poems, exercised no influence on the
Romantic Revival—see for example The Cambridge History of English Literature,
Vol. XI, 201. Yet we know that his work was known to and appreciated by
Wordsworth, Coleridge, Lamb, Southey, and Hayley. (Although little regarded now,
Hayley’s fame was then so great that he was offered and refused the poet-
laureateship. He appears to be the one man who was an intimate friend of both
Blake and Cowper.) While a very long period went by before Blake’s poems
became generally known, their influence may well have been very great,
permeating unconsciously through other minds. See reference on p. 194 to the
similar case of Fitzgerald’s “Omar Khayyam.”
Even if a poem were read by only one person, it might conceivably influence a
generation of authors. Suppose, if that had been possible, a page of Swinburne’s
“Tristram of Lyonesse” or F. W. H. Myers’ “Implicit Promise” (both quoted
elsewhere) had been read by Pope or Dryden; how the monotonous heroic couplet
of their time might have been transformed!
R. Hodgson, 1879.
An impromptu written when the mother and child incident happened and not
revised.
Humanity is neither a love for the whole human race, nor a love
for each individual of it, but a love for the race, or for the ideal of
man, in each individual. In other and less pedantic words, he who is
truly humane considers every human being as such interesting and
important, and without waiting to criticize each individual specimen,
pays in advance to all alike the tribute of good wishes and
sympathy.... If some human beings are abject and contemptible, if it
be incredible to us that they can have any high dignity or destiny, do
we regard them from so great a height as Christ? Are we likely to be
more pained by their faults and deficiencies than he was? Is our
standard higher than his? And yet he associated by preference with
these meanest of the race; no contempt for them did he ever
express, no suspicion that they might be less dear than the best and
wisest to the common Father, no doubt that they were naturally
capable of rising to a moral elevation like his own. There is nothing
of which a man may be prouder than of this; it is the most hopeful
and redeeming fact in history; it is precisely what was wanting to
raise the love of man as man to enthusiasm. An eternal glory has
been shed upon the human race by the love Christ bore to it.
Sir J. R. Seeley (Ecce Homo).
On parent knees, a naked, new-born child,
Weeping thou sat’st while all around thee smiled:
So live, that sinking to thy life’s last sleep
Calm thou mayst smile, while all around thee weep.
This was quoted by Lord Lytton in an essay on The Influence of Love upon
Literature and Real Life.
This is the poet’s vision of the city of the future, and will be interesting to the
allotment-holders in English cities to-day.
Dear dead women, with such hair, too—what’s become of all the
gold
Used to hang and brush their bosoms? I feel chilly and grown
old.
...
R. Browning (Pauline).
S. T. Coleridge (Christabel)
But his wings will not rest and his feet will not stay for us;
Morning is here in the joy of its might;
With his breath has he sweetened a night and a day for us;
Now let him pass and the myrtles make way for us;
Love can but last in us here at his height
For a day and a night.
In the story Dorothea has found her husband to be a man of narrow mind and
unsympathetic nature. Such a disillusionment after marriage frequently happens,
and we are not deeply moved by what is not unusual, although it may mean a real
life-tragedy. Ruskin says “God gives the disposition to every healthy human mind
in some degree to pass over or even harden itself against evil things, else the
suffering would be too great to be borne” (Modern Painters v., xix., 32). Only thus
could we have lived through the horrors of the present war.
George Eliot’s analogy between intensity of the emotions and acuteness of the
senses reminds one of Pope’s lines (“Essay on Man,” Ep. I.) where he says life
would be insupportable, if we had the acute hearing, smell and other senses of
insects and other animals; we should
But here is the finger of God, a flash of the will that can,
Existent behind all laws, that made them and, lo, they are!
And I know not if, save in this, such gift be allowed to man,
That out of three sounds he frame, not a fourth sound, but a
star.
Consider it well: each tone of our scale in itself is nought;
It is everywhere in the world—loud, soft, and all is said:
Give it to me to use! I mix it with two in my thought:
And, there! Ye have heard and seen: consider and bow the
head!
See the preceding note. The poet says that Painting and Poetry are “art in
obedience to laws,” but the musician exerts a higher creative will akin to that of
God. The painter has before him the pictures he reproduces, the poet borrows his
imagery from visible things and has apt words in which to express his thoughts:
the musician has nothing visible, nothing outside his own soul, to assist him, and
can use only the meaningless sounds which we hear everywhere around us. By
combining, however, three of those empty sounds (in a chord) he evolves a fourth
sound, which so transcends all that other arts can do in expressing emotion that
Browning compares it to a “star.”
But this expresses only part of the poet’s meaning. In using this tremendous
comparison to a star, as also in enthroning music supreme above art and poetry,
he means that it transcends their loftiest flights and rises above our world to the
heavens above. In the earlier part of the poem the “pinnacled glory” built by the
slaves of sound at the bidding of the musician’s soul is based “broad on the roots
of things” and ascends until it “attains to heaven.”
F. W. H. Myers, in “The Renewal of Youth,” has a passage on music. His theme is
that while music (as in Mozart’s operas) may express human passion, it also (as in
Beethoven) rises to greater heights and appears to voice the emotions of a world
beyond our senses. In the lines I have italicized in the following passage he no
doubt refers to Browning’s line, “That out of three sounds he frame, not a fourth
sound, but a star!”—the “star” meaning that music ascends to a higher world than
our own:—
Not only does Browning unselfishly assert that the sister-art is superior to his
own, but he goes further, and doubts if music is not the greatest of all man’s gifts.
I do not discuss either contention—leaving musicians to rejoice in the tribute of a
great poet.
Although a gem be cast away,
And lie obscured in heaps of clay,
Its precious worth is still the same;
Although vile dust be whirled to heaven,
To it no dignity is given,
Still base as when from earth it came.
Tennyson (Ulysses).
Jenny kissed me when we met,
Jumping from the chair she sat in;
Time, you thief, who love to get
Sweets into your list, put that in!
Say I’m weary, say I’m sad.
Say that health and wealth have missed me,
Say I’m growing old, but add
Jenny kissed me.
Leigh Hunt.
From Guy Mannering. Scott says it is a prayer or spell, which was used in
Scotland or Northern England to speed the passage of a parting spirit, like the
tolling of a bell in Catholic days.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com