Get JavaScript Design Patterns 1 / Converted Edition Hugo Di Francesco PDF Ebook With Full Chapters Now
Get JavaScript Design Patterns 1 / Converted Edition Hugo Di Francesco PDF Ebook With Full Chapters Now
com
https://textbookfull.com/product/javascript-
design-patterns-1-converted-edition-hugo-di-
francesco/
https://textbookfull.com/product/javascript-patterns-build-better-
applications-with-coding-and-design-patterns-1st-edition-stefanov-
stoyan/
textbookfull.com
https://textbookfull.com/product/learning-opentelemetry-1-converted-
edition-ted-young/
textbookfull.com
https://textbookfull.com/product/the-political-anatomy-of-
domination-1st-edition-beatrice-hibou-auth/
textbookfull.com
Socio cultural Inspired Metaheuristics Anand J. Kulkarni
https://textbookfull.com/product/socio-cultural-inspired-
metaheuristics-anand-j-kulkarni/
textbookfull.com
https://textbookfull.com/product/the-ottomans-and-the-mamluks-
imperial-diplomacy-and-warfare-in-the-islamic-world-muslu/
textbookfull.com
https://textbookfull.com/product/mathematical-statistics-1st-edition-
dieter-rasch/
textbookfull.com
https://textbookfull.com/product/oswaal-cbse-question-bank-
class-12-biology-chapterwise-topicwise-for-march-2020-exam-oswaal-
editorial-board/
textbookfull.com
https://textbookfull.com/product/make-me-a-daddy-1st-edition-m-k-
moore/
textbookfull.com
The Psychology of Humor An Integrative Approach Rod A.
Martin
https://textbookfull.com/product/the-psychology-of-humor-an-
integrative-approach-rod-a-martin/
textbookfull.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!
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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) {
Random documents with unrelated
content Scribd suggests to you:
“Pansies for thought, sleep as you ought,
Sleep, but awake for your true lover’s sake,”
Page 38
of the simple chambreys in which changed to
of the simple chambrays in which
Page 43
green and white chambrey changed to
green and white chambray
Page 64
tell their wards it is somethng changed to
tell their wards it is something
Page 141
in all it’s vineclad life changed to
in all its Vineclad life
Page 170
through the vineclad streets changed to
through the Vineclad streets
Page 172
its size unobstrusive changed to
its size unobtrusive
Page 205
in the Roman colosseum changed to
in the Roman Colosseum
Page 259
squat wedgewood teapot changed to
squat Wedgewood teapot
Page 316
You musn’t say a word changed to
You mustn’t say a word
*** END OF THE PROJECT GUTENBERG EBOOK HOLLYHOCK
HOUSE: A STORY FOR GIRLS ***
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in paragraph
1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.