Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

JavaScript Design Patterns Hugo Di

Francesco
Visit to download the full and correct content document:
https://ebookmass.com/product/javascript-design-patterns-hugo-di-francesco/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Analysis and Design of Prestressed Concrete Di Hu

https://ebookmass.com/product/analysis-and-design-of-prestressed-
concrete-di-hu/

Design patterns: elements of reusable object-oriented


software Gamma

https://ebookmass.com/product/design-patterns-elements-of-
reusable-object-oriented-software-gamma/

JavaScript T. J. Crowder

https://ebookmass.com/product/javascript-t-j-crowder/

Architecting ASP.NET Core Applications Carl-Hugo


Marcotte

https://ebookmass.com/product/architecting-asp-net-core-
applications-carl-hugo-marcotte/
Learning Web Design: A Beginner’s Guide to HTML, CSS,
JavaScript, and Web Graphics 5th Edition, (Ebook PDF)

https://ebookmass.com/product/learning-web-design-a-beginners-
guide-to-html-css-javascript-and-web-graphics-5th-edition-ebook-
pdf/

The Transhumanist Movement Francesco Paolo Adorno

https://ebookmass.com/product/the-transhumanist-movement-
francesco-paolo-adorno/

Oxford Textbook of Cancer Biology Francesco Pezzella

https://ebookmass.com/product/oxford-textbook-of-cancer-biology-
francesco-pezzella/

Eloquent JavaScript 4th Edition Marijn Haverbeke

https://ebookmass.com/product/eloquent-javascript-4th-edition-
marijn-haverbeke/

Blue Hunger Viola Di Grado

https://ebookmass.com/product/blue-hunger-viola-di-grado/
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.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Kushal Dave

Senior Content Development Editor: Feza Shaikh

Technical Editor: Simran Udasi

Copy Editor: Safis Editing

Project Coordinator: Aishwarya Mohan

Indexer: Subalakshmi Govindhan

Production Designer: Jyoti Kadam

Marketing Coordinators: Nivedita Pandey and Anamika Singh

First published: March 2024

Production reference: 1150224


Published by Packt Publishing Ltd.

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

About the author


Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds an
MEng degree in mathematical computation from University College London (UCL). He has used
JavaScript across the stack to create scalable and performant platforms at companies such as Canon
and Elsevier, and in industries such as print on demand and mindfulness. He is currently tackling
problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes, while
running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in
the pursuit of which he trains and competes across the globe.
I want to thank all the people who have supported me in my life and writing journey,
particularly my wife Amalia, and my family.

About the reviewers


Dr. Murugavel, a distinguished and versatile educator in the realms of computer science engineering
and information technology. With over 13 years of enriching experience at renowned universities and
an additional 8+ years dedicated to the dynamic field of data analytics, Dr. Murugavel stands as a
beacon of expertise at the intersection of academia and technology.

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

Working with Creational Design Patterns


What are creational design patterns?
Implementing the prototype pattern in JavaScript
Implementation
A use case
The singleton pattern with eager and lazy initialization in
JavaScript
Implementation
Use cases
Improvements with the “class singleton” pattern
A singleton without class fields using ES module behavior
The factory pattern in JavaScript
Implementation
Use cases
Improvements with modern JavaScript
Summary

Implementing Structural Design Patterns


Technical requirements
What are structural design patterns?
Implementing the Proxy pattern with Proxy and Reflect
A redaction proxy implementation
Use cases
Improving the proxy pattern in JavaScript with the Proxy and
Reflect global objects
Decorator in JavaScript
Implementation
Use cases
Improvements/limitations
Flyweight in JavaScript
Implementation
Use cases
Improvements/limitations
Adapter in JavaScript
Use cases
Improvements/limitations
Summary

Leveraging Behavioral Design Patterns


Technical requirements
What are behavioral design patterns?
The observer pattern in JavaScript
Implementation
Use cases of the observer pattern
Limitations and improvements
State and strategy in JavaScript and a simplified approach
Implementation
Use cases of the state and strategy patterns
Limitations and improvements
Visitor in JavaScript
Implementation
Use cases of the visitor pattern
Summary
Part 2: Architecture and UI Patterns

Exploring Reactive View Library Patterns


Technical requirements
What are reactive view library patterns?
The render prop pattern
Use cases
Implementation/example
Limitations
The higher-order component pattern
Implementation/example
Use cases
Limitations
The hooks pattern
An implementation/example
Use cases
Limitations
The provider pattern
Use case – the prop drilling problem
An implementation/example
Limitations
Summary

Rendering Strategies and Page Hydration


Technical requirements
Client and server rendering with React
Client-side rendering in React
Server rendering in React
Trade-offs between client and server rendering
Static rendering with Next.js
Automatic static generation
Static generation with a third-party data source
Static generation with dynamic paths
Page hydration strategies
Common React rehydration issues
React streaming server-side rendering
Summary

Micro Frontends, Zones, and Islands Architectures


Technical requirements
An overview of micro frontends
Key benefits
“Classic” micro frontend patterns
Other concerns in a micro frontend world
Composing applications with Next.js “zones”
Root app
Adding a /search app
Adding /checkout app
The benefits/supporting team scaling
The drawbacks of Next.js zones
Scaling performance-sensitive pages with the “islands”
architecture
Islands setup with is-land
Product island
Cart island
A related products island
Scaling with a team – bundling islands
Drawbacks
Summary
Part 3: Performance and Security Patterns

Asynchronous Programming Performance Patterns


Technical requirements
Controlling sequential asynchronous operations with
async/await and Promises
Parallel asynchronous operation patterns
Asynchronous cancellation and timeouts with AbortController
Throttling, debouncing, and batching asynchronous operations
Summary

Event-Driven Programming Patterns


Technical requirements
Optimizing event listeners through event delegation
Patterns for secure frame/native WebView bridge messaging
Event listener performance antipatterns
Summary

Maximizing Performance – Lazy Loading and Code


Splitting
Technical requirements
Dynamic imports and code splitting with Vite
Route-based code splitting and bundling
Loading JavaScript on element visibility and interaction
Summary

10

Asset Loading Strategies and Executing Code off the


Main Thread
Technical requirements
Asset loading optimization – async, defer, preconnect, preload,
and prefetch
Using Next.js Script’s strategy option to optimize asset loading
Loading and running scripts in a worker thread
Summary

Index

Other Books You May Enjoy


Preface
Welcome! JavaScript design patterns are techniques that allow us to write more robust, scalable, and
extensible applications in JavaScript. JavaScript is the main programming language available in web
browsers and is one of the most popular programming languages with support beyond browsers.

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.

JavaScript’s attributes as a lightweight, multi-paradigm, dynamic, single-threaded language give it


different strengths and weaknesses to other mainstream programming languages. It’s common for
software engineers to use JavaScript in addition to being well versed in a different programming
language. JavaScript’s different gearing means that implementing design patterns verbatim can lead
to non-idiomatic and under-performing JavaScript applications.

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 7, Asynchronous Programming Performance Patterns, looks at how JavaScript’s single-


threaded event-loop-based concurrency model is one of its greatest strengths but is often
misunderstood or under-leveraged in performance-sensitive situations. Writing asynchronous-
handling code in JavaScript in a performant and extensible manner is key to delivering a smooth user
experience at scale.

Chapter 8, Event-Driven Programming Patterns, explores how event-driven programming in


JavaScript is of paramount importance in security-sensitive applications as it is a way to pass
information from and to different web contexts. Event-driven applications can often be optimized to
enable better performance and scalability.

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.

To get the most out of this book


You will need to have prior experience with JavaScript and developing for the web. Some of the
more advanced topics in the book will be of interest to developers with intermediate experience in
building for the web with JavaScript.

Software/hardware covered in the book Operating system requirements

Node.js 20+ Windows, macOS, or Linux

NPM v8+ Windows, macOS, or Linux

ECMAScript 6+ Windows, macOS, or Linux

React v16+ Windows, macOS, or Linux

Next.js Windows, macOS, or Linux

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.

Download the example code files


You can download the example code files for this book from GitHub at
https://github.com/PacktPublishing/JavaScript-Design-Patterns. If there’s an update to the code, it
will be updated in the GitHub repository.

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.”

A block of code is set as follows:

<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.”

TIPS OR IMPORTANT NOTES


Appear like this.

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
customercare@packtpub.com 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
copyright@packt.com 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.

Share Your Thoughts


Once you’ve read JavaScript Design Patterns, we’d love to hear your thoughts! Please click here to
go straight to the Amazon review pagefor this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering
excellent quality content.

Download a free PDF copy of this book


Thanks for purchasing this book!

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

Follow these simple steps to get the benefits:


1. Scan the QR code or visit the link below

https://packt.link/free-ebook/978-1-80461-227-9

2. Submit your proof of purchase

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.

This part has the following chapters:


Chapter 1, Working with Creational Design Patterns

Chapter 2, Implementing Structural Design Patterns

Chapter 3, Leveraging Behavioral Design Patterns


1

Working with Creational Design Patterns


JavaScript design patterns are techniques that allow us to write more robust, scalable, and extensible
applications in JavaScript. JavaScript is a very popular programming language, in part due to its
place as a way to deliver interactive functionality on web pages. The other reason for its popularity is
JavaScript’s lightweight, dynamic, multi-paradigm nature, which means that design patterns from
other ecosystems can be adapted to take advantage of JavaScript’s strengths. JavaScript’s specific
strengths and weaknesses can also inform new patterns specific to the language and the contexts in
which it’s used.

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.

We’ll cover the following topics in this chapter:


A comprehensive definition of creational design patterns and definitions for the prototype, singleton, and factory patterns

Multiple implementations of the prototype pattern and its use cases

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.

What are creational design patterns?


Creational design patterns handle object creation. They allow a consumer to create object instances
without knowing the details of how to instantiate the object. Since, in object-oriented languages,
instantiation of objects is limited to a class’s constructor, allowing object instances to be created
without calling the constructor is useful to reduce noise and tight coupling between the consumer and
the class being instantiated.
In JavaScript, there’s ambiguity when we discuss “object creation,” since JavaScript’s multi-
paradigm nature means we can create objects without a class or a constructor. For example, in
JavaScript this is an object creation using an object literal – const config = { forceUpdate: true }.

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.

Implementing the prototype pattern in JavaScript


Let’s start with a definition of the prototype pattern first.

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.

A BoardSquare class constructor might look like the following:

class BoardSquare {
constructor(color, row, file, startingPiece) {
this.color = color;
this.row = row;
this.file = file;
}
}

A set of useful methods on BoardSquare might be occupySquare and clearSquare, as follows:

class BoardSquare {
// no change to the rest of the class
occupySquare(piece) {
this.piece = piece;
}
clearSquare() {
this.piece = null;
}
}

Instantiating BoardSquare is quite cumbersome, due to all its properties:

const whiteSquare = new BoardSquare('white');


const whiteSquareTwo = new BoardSquare('white');
// ...
const whiteSquareLast = new BoardSquare('white');

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:

const blackSquare = new BoardSquare('black');


const blackSquareTwo = new BoardSquare('black');
// ...
const blackSquareLast = new BoardSquare('black');

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;
}
}

Using BoardSquarePrototype requires the following steps:


1. First, we want an instance of BoardSquare to initialize – in this case, with 'white'. It will then be passed as the
prototype property during the BoardSquarePrototype constructor call:

const whiteSquare = new BoardSquare('white');


const whiteSquarePrototype = new BoardSquarePrototype
(whiteSquare);

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.

const whiteSquareTwo = whiteSquarePrototype.clone();


// ...
const whiteSquareLast = whiteSquarePrototype.clone();
console.assert(
whiteSquare.color === whiteSquareTwo.color &&
whiteSquareTwo.color === whiteSquareLast.color,
'Prototype.clone()-ed instances have the same color
as the prototype'
);
console.assert(
whiteSquare !== whiteSquareTwo &&
whiteSquare !== whiteSquareLast &&
whiteSquareTwo !== whiteSquareLast,
'each Prototype.clone() call outputs a different
instances'
);

Per the assertions in the code, the cloned instances contain the same value for color but are different
instances of the Square object.

A use case
To illustrate what it would take to change from a white square to a black square, let’s look at some
sample code where 'white' is not referenced in the variable names:

const boardSquare = new BoardSquare('white');


const boardSquarePrototype = new BoardSquarePrototype(boardSquare);
const boardSquareTwo = boardSquarePrototype.clone();
// ...
const boardSquareLast = boardSquarePrototype.clone();
console.assert(
boardSquareTwo.color === 'white' &&
boardSquare.color === boardSquareTwo.color &&
boardSquareTwo.color === boardSquareLast.color,
'Prototype.clone()-ed instances have the same color as
the prototype'
);
console.assert(
boardSquare !== boardSquareTwo &&
boardSquare !== boardSquareLast &&
boardSquareTwo !== boardSquareLast,
'each Prototype.clone() call outputs a different
instances'
);

In this scenario, we would only have to change the color value passed to BoardSquare to change the
color of all the instances cloned from the prototype:

const boardSquare = new BoardSquare('black');


// rest of the code stays the same
console.assert(
boardSquareTwo.color === 'black' &&
boardSquare.color === boardSquareTwo.color &&
boardSquareTwo.color === boardSquareLast.color,
'Prototype.clone()-ed instances have the same color as
the prototype'
);
console.assert(
boardSquare !== boardSquareTwo &&
boardSquare !== boardSquareLast &&
boardSquareTwo !== boardSquareLast,
'each Prototype.clone() call outputs a different
instances'
);

The prototype pattern is useful in situations where a “template” for the object instances is useful. It’s
a good pattern to create a “default object” but with custom values. It allows faster and easier changes,
since they are implemented once on the template object but are applied to all clone()-ed instances.
Increasing robustness to change in the prototype’s instance
variables with modern JavaScript
There are improvements we can make to our prototype implementation in JavaScript.

The first is in the clone() method. To make our prototype class robust to changes in the prototype’s
constructor/instance variables, we should avoid copying the properties one by one.

For example, if we add a new startingPiece parameter that the BoardSquare constructor takes and
sets the piece instance variable to, our current implementation of BoardSquarePrototype will fail to
copy it, since it only copies color, row, and file:

class BoardSquare {
constructor(color, row, file, startingPiece) {
this.color = color;
this.row = row;
this.file = file;
this.piece = startingPiece;
}
// same rest of the class
}
const boardSquare = new BoardSquare('white', 1, 'A',
'king');
const boardSquarePrototype = new BoardSquarePrototype
(boardSquare);
const otherBoardSquare = boardSquarePrototype.clone();
console.assert(
otherBoardSquare.piece === undefined,
'prototype.piece was not copied over'
);

NOTE
Reference for Object.assign: https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign.

If we amend our BoardSquarePrototype class to use Object.assign(new BoardSquare(),

this.prototype), it will copy all the enumerable properties of prototype:

class BoardSquarePrototype {
constructor(prototype) {
this.prototype = prototype;
}
clone() {
return Object.assign(new BoardSquare(), this.prototype);
}
}
const boardSquare = new BoardSquare('white', 1, 'A',
'king');
const boardSquarePrototype = new BoardSquarePrototype
(boardSquare);
const otherBoardSquare = boardSquarePrototype.clone();
console.assert(
otherBoardSquare.piece === 'king' &&
otherBoardSquare.piece === boardSquare.piece,
'prototype.piece was copied over'
);
The prototype pattern without classes in JavaScript
For historical reasons, JavaScript has a prototype concept deeply embedded into the language. In fact,
classes were introduced much later into the ECMAScript standard, with ECMAScript 6, which was
released in 2015 (for reference, ECMAScript 1 was published in 1997).

This is why a lot of JavaScript completely forgoes the use of classes. The JavaScript “object
prototype” can be used to make objects inherit methods and variables from each other.

One way to clone objects is by using the Object.create to clone objects with their methods. This
relies on the JavaScript prototype system:

const square = {
color: 'white',
occupySquare(piece) {
this.piece = piece;
},
clearSquare() {
this.piece = null;
},
};
const otherSquare = Object.create(square);

One subtlety here is that Object.create does not actually copy anything; it simply creates a new
object and sets its prototype to square. This means that if properties are not found on otherSquare,
they’re accessed on square:

console.assert(otherSquare.__proto__ === square, 'uses JS


prototype');
console.assert(
otherSquare.occupySquare === square.occupySquare &&
otherSquare.clearSquare === square.clearSquare,
"methods are not copied, they're 'inherited' using the
prototype"
);
delete otherSquare.color;
console.assert(
otherSquare.color === 'white' && otherSquare.color ===
square.color,
'data fields are also inherited'
);
A further note on the JavaScript prototype, and its existence before classes were part of JavaScript, is
that subclassing in JavaScript is another syntax for setting an object’s prototype. Have a look at the
following extends example. BlackSquare extends Square sets the prototype.__proto__ property of
BlackSquare to Square.prototype:

class Square {
constructor() {}
occupySquare(piece) {
this.piece = piece;
}
clearSquare() {
this.piece = null;
}
}
class BlackSquare extends Square {
constructor() {
super();
this.color = 'black';
}
}
console.assert(
BlackSquare.prototype.__proto__ === Square.prototype,
'subclass prototype has prototype of superclass'
);

In this section, we learned how to implement the prototype pattern with a prototype class that exposes
a clone() method, which code situations the prototype patterns can help with, and how to further
improve our prototype implementation with modern JavaScript features. We also covered the
JavaScript “prototype,” why it exists, and its relationship with the prototype design pattern.

In the next part of the chapter, we’ll look at another creational design pattern, the singleton design
pattern, with some implementation approaches in JavaScript and its use cases.

The singleton pattern with eager and lazy initialization


in JavaScript
To begin, let’s define the singleton design pattern.

The singleton pattern allows an object to be instantiated only once, exposes this single instance to
consumers, and controls the instantiation of the single instance.

The singleton is another way of getting access to an object instance without using a constructor,
although it’s necessary for the object to be designed as a singleton.

Implementation
Another random document with
no related content on Scribd:
executed; and, if Diodorus’ story be true, the Phœnicians were so
alarmed at the prospect of what might happen to them from the
angry Xerxes that, after retiring to Phaleron in the afternoon, they
fled in a body under cover of night to the Asian coast. As, however,
no trace of such a detail is found in any other historian, and their
statements are wholly inconsistent with it, it cannot be regarded as
serious history.
It was not, perhaps, until after the war was over that the Greeks
acquired sufficient perspective to gauge aright the full significance of
their victory on this day. It absolutely destroyed the very foundation
of the great strategical plan on which the invasion had been
170
conducted—the combined action of the fleet and army. Never,
perhaps, has the influence of sea-power been more strikingly
exemplified in warfare than in the total reverse of circumstances
which resulted from Salamis. Up to this time the naval power of
Persia had been supreme in the Ægean and Eastern Mediterranean
for many years past; and the attempt which the Ionians had made to
break it at Ladé had by the completeness of its failure merely served
to establish it on a firmer basis. But from Salamis onward the decline
was rapid, and the Persian navy was never again as an unaided unit
formidable in the Ægean.
Salamis was also decisive of the war in which it was fought.
Having lost the command of the sea, the Persians could not possibly
maintain, in a poor country such as Greece, the overwhelming land
force with which they had invaded it. The mere question of supplies
rendered the rapid withdrawal of the major part of it an imperative
necessity. Persia did not, indeed, give up the
MARATHON,
SALAMIS, AND
struggle, but she was obliged to continue it
PLATÆA. with a force so reduced in numbers that the
Greeks were able to match it in fighting, if not
in actual numerical strength. Salamis was the turning-point of the
war. Platæa was the consummation of Salamis. After Salamis
Southern Greece was safe. Mardonius might have maintained
himself for some time in the rich lands of Bœotia, he might even
have attempted to include that region within the imperial frontier, but
he could not have carried on a sustained campaign in the poor
districts to the south of the line of Kithæron-Parnes line. The
salvation of the North was won at Platæa.
In consideration of the circumstances, is it presumptuous to
hazard the opinion that Sir Edward Creasy was not wholly justified in
preferring Marathon to Salamis as one of the “fifteen decisive battles
of the World”? The decisive battles exemplified in his book are, with
the exception of Marathon, chosen apparently as marking the time at
which the tide of affairs of world-wide moment definitely turned to an
uninterrupted ebb or flow. But they are in nearly every case the
outcome of a chain of events extending, in many instances, over a
series of preceding years. If the first link in the chain is to be
regarded as decisive of the whole series of events, then, perhaps,
the choice of Marathon may be justified; but, on the same principle of
choice, the decisive battles of the world would have in many cases to
be sought for in comparatively obscure engagements. But if, as is
the case with most of the instances Sir Edward Creasy adduces, the
supreme decisive moment in a great situation is to be taken, then
Salamis, not Marathon, is to be chosen in the great Persian war of
the first quarter of the fifth century. The actual records of the time
conspicuously fail to support the view that from Marathon onward the
tide of the struggle with Persia flowed uninterruptedly in favour of the
Greeks.
CHAPTER X.
FROM SALAMIS TO PLATÆA.
After the defeat of Salamis, the position of the whole Persian
expedition was one of extreme danger. The command of the sea had
been lost for the time being, and the chances of its recovery were
remote. A fleet which had been so severely handled was not likely to
fight so well on a second occasion, even if it were possible to induce
it to assume once more the offensive. It was infinitely more probable
that the Greeks, who had hitherto acted almost entirely on the
defensive, would now realize that they were in a position to become
the attacking party. The question of the moment seemed to be how
the Persian naval force could make good its retreat without exposing
itself to further, and, it might be, irreparable, disaster. Xerxes, with
the characteristic selfishness of a despot, seems to have concerned
himself with making his own escape secure, and to have merely
troubled himself about that of the fleet in so far as his own safety
was dependent upon it. He had reason to doubt the loyalty of the
Ionian contingent. It had, indeed, fought well in the battle; but the
reverse which had been experienced would inevitably tend to
quicken whatever element of disloyalty it contained. His main anxiety
was for the bridge across the Hellespont.
The account which Herodotus gives of the measures which he
took to give the Greeks the impression that he meditated a second
attack, and to hide his intention to retreat, is of so strange a
character that it has been largely discredited by modern authorities.
“He set to work,” says the historian, “to carry a
PERSIAN COUNCIL
mole across to Salamis, and he tied
OF WAR.
Phœnician merchant-ships together, to act as
H. viii. 97. pontoons, and as a defence. He further prepared for
battle, as though about to fight a second sea-fight.”
These preparations, so it is said, deceived all his own people save
Mardonius, who, knowing his master well, was not under any illusion
171
as to his real intentions.

H. viii. 100.
The evident alarm and despair with which Xerxes
regarded the situation rendered Mardonius uneasy. An
adviser whose counsels had ended in disaster,—and he was mainly
responsible for persuading the king to undertake the great
expedition,—might well be anxious as to the consequences which
the failure might have for himself. Whether Herodotus had any real
authority for his account of the advice which he represents
Mardonius to have given Xerxes at this time, may perhaps be
suspected; but the main outlines of it are worth quoting, even if they
only reproduce what some contemporary Greek imagined that
advice to have been. He is represented, in the first place, as seeking
to minimize the disaster by arguing that it had only fallen upon one
branch of the service, and that the land-army was in no wise
impaired in efficiency by what had happened. If he did actually use
this argument, he can only have used it because he thought that it
was a sufficiently good one for the man to whom he was speaking.
He had himself commanded the expedition of 492; and though on a
much smaller scale, that venture had been brought to a premature
conclusion by the storm which wrecked his fleet off Mount Athos.
Mardonius was the last man who ought to have deceived himself as
to the significance of the disaster at Salamis. Two courses, he said,
were still open,—either to march with the whole army against the
Peloponnese, or for Xerxes to withdraw with the major part of the
land-forces, and leave him three hundred thousand men wherewith
to complete the conquest of Greece. Such is the advice as reported.
Whether a march on Peloponnese was possible at this time cannot
be said, since the state of the Persian supplies is not known. In any
case, Xerxes had no stomach for such a venture, and adopted the
alternative suggestion, which offered a greater chance of security to
H. viii 102.
his all-important self. Moreover, this was the view of
the matter which the astute Artemisia, whom he called
172
into counsel, put before him.
It must of necessity remain a matter for doubt whether Mardonius
ever gave such advice. The retirement of the fleet to the Asian coast
would give the Greeks the naval command of their side of the
Ægean, and, that being so, the real line of communications was lost,
and the alternative route by land along the North Ægean would be,
even if it could be regarded as effective, liable to be cut by an attack
from the sea. On the other hand, it is possible that he reckoned that
he might maintain himself for some months, even for a year, on the
food-resources of Thessaly and Bœotia; and in that space of time
much might happen to reverse the ill-fortune of the moment. Besides
all this, even if the conquest of Greece as a whole could not be
effected, there did remain the possibility of advancing the Persian
frontier south from Macedonia even as far as Kithæron, and of
robbing Greece of her richest lands. That the Greeks feared
something of this kind is shown by their subsequent advance to
Platæa. That move was so inconsistent with the whole plan on which
they had conducted the campaign on land, that it can only be
accounted for on the hypothesis that they were actuated by some
such fear.
But there were also political considerations
THEMISTOCLES
AFTER SALAMIS.
of the very highest importance which could not
but affect the decision of Xerxes and the
Persian authorities. The acknowledgment of complete failure such as
would have been apparent had the whole force withdrawn en masse
to Asia, must have shaken to its very foundations the great
composite empire which was held together by the strong hand and
the prestige of success. But could Xerxes on his return report that a
force had been left to complete the reduction of Greece, the
magnitude of the disaster which had fallen upon him might be
concealed, until, at any rate, he was himself in a position to take
measures to provide against any possible commotion which might be
caused when the varied population of the empire came to realize the
extent of the failure which had resulted in an expedition in which it
had put forth all its strength. Whatever the advice of Mardonius may
have been, these considerations must have been present with
Xerxes and his council when they met to discuss the course to be
adopted in view of what had happened at Salamis. Herodotus
shows, from the words he attributes to Artemisia, that he was not
173
oblivious to the wider possibilities of the situation.
His account of the events which immediately resulted from
Xerxes’ decision is complicated historically by the reappearance of
Themistocles on the stage of his history. The historian does not
attempt to conceal the prominence of that great man at Salamis; but
in the description of the actual fighting his name is only incidentally
mentioned, and personal details of him are conspicuous by their
absence. But the tradition of the events succeeding the battle
contained several ugly stories, some of them, indeed, capable of
diverse interpretation, but all of them capable of being interpreted to
Themistocles’ discredit. These the historian has inserted in his
narrative, with the result that he has introduced into it an element
which must excite suspicion, and which makes it very difficult to
disentangle that in it which is reliable from that which is not so.

H. viii. 107.
On the very night, it is said, after Xerxes’ decision
had been taken, the commanders of the Persian fleet
put out with all speed for the Hellespont, with orders to guard the
bridge across the strait for the king’s return. It is not, perhaps, easy
to see why so much store should be set by the bridge. The main
point, it might have been imagined, would be to defend the
Hellespont. Xerxes’ personal safety and his passage of the strait
would in that case have been equally well secured.
One incident of the voyage is described which is intended to
demonstrate the nervous state to which the Persian seamen had
been reduced by their defeat. Near a place called Zoster, which is
supposed to have been situated on the Attic coast the Persians
mistook certain rocks for enemies’ ships, and fled “a long distance”
before they discovered their mistake. The object of the story is
evidently to emphasize the dramatic contrast between the
confidence which preceded the battle and the depression which
succeeded it.
The next day was well advanced before the Greeks discovered
the flight. Seeing the land-army in its old position, they supposed the
Persian fleet to be still at Phaleron, which bay would be hidden from
their position in the strait by the high promontory of the Piræus; and,
under this impression, they prepared to meet a second attack. It is
remarkable, but quite evident, that the Greeks under-estimated alike
the moral and material damage they had inflicted on the enemy.
They show none of the jubilation which follows a decisive victory;
and it must be concluded that the fight was more fierce and more
stubborn on the part of the vanquished than any Greek historian has
described it to have been. Then, says Herodotus, when they
discovered that the fleet had sailed away, they started in pursuit, and
proceeded as far as Andros without catching sight of it. This is not
surprising, considering that it had, in all probability, twelve hours’
start. The statement that the fleet went as far as Andros, or even
ventured to leave Salamis at this time, has been regarded with
suspicion by some historians. It is argued that
QUESTIONS OF THE
with the land-army of the Persians still in
HELLESPONT
BRIDGE. Attica, the Greeks could not have ventured to
withdraw their fleet from the strait, and have
exposed the refugees on Salamis to attack.
But is it necessarily to be assumed that the Greeks did not leave
any vessels behind to provide against such a contingency? It may
even be doubted whether, after the withdrawal of the fleet, the
Persian army had any means whatever at its disposal for the
passage of the strait.
The short voyage to Andros was, no doubt, of the nature of a
reconnaissance. It was manifestly important to know whether the
enemy’s ships had definitely departed from Greek waters.

H. viii. 108. On arriving at Andros a Council of War was held as


to the plan of operations for the immediate future.
Themistocles’ view was that the pursuit should be continued, and
that the bridge over the Hellespont should be destroyed. Eurybiades
urged, on the other hand, that if the Persian army were thus cut off
from its sole avenue of retreat, it must remain in Europe, and would
be compelled to develop a policy of great activity for the mere
purpose of obtaining supplies. The result of this, so he thought,
would be the gradual subjection of the land, and the destruction of
the annual produce of Greece. He therefore urged that the way of
escape be left open. With him, as might be expected, the other
Peloponnesian commanders agreed.
Themistocles, finding he could not prevail upon the Greeks as a
body to adopt his plan, then addressed the Athenians, who were, so
Herodotus says, eager to sail at once to the Hellespont, and ready to
take the risk of so doing upon their own shoulders. His address is
given in what profess to be the actual words of it. So far from urging
them to follow out their desires, he emphatically dissuades them
from this course; thus, apparently, completely reversing the advice
he had first given. The change of counsel is plainly explicable on the
ground that what he considered to be the best course for the fleet as
a whole would, he thought, be risky and unadvisable for half the fleet
to attempt But that is very far from being the interpretation which
H. viii. 109.
Herodotus puts upon it. “This,” says the historian, “he
said with the intention of establishing a claim upon the
Persian, in order that, in case any disaster should befall him at the
hands of the Athenians, he might have a place of retreat. In saying
H. viii. 110.
this, Themistocles dissembled, but the Athenians
believed him: for inasmuch as he had, previous to the
recent events, been regarded as a clever man, and his cleverness
and wisdom had been clearly confirmed by what had lately
happened, they were ready to listen to what he said.”
There can be little doubt that this tale is part of that unveracious
Themistocles legend which Herodotus has woven into those
traditions of the great war which he has followed in composing his
history. Never is the animus against Themistocles more clearly
shown; and in no instance is the absolute improbability of any single
part of the legend more strikingly displayed. The tale is refuted by its
context. Before starting for Andros, the Greeks had been deceived
as to the movements of the Persian fleet, by observing the land-army
in its original position. And yet, arrived at Andros, Themistocles is
represented as actually proposing to cross the Ægean and cut off
the retreat of an army whose retreat had not begun, and whose
intention to retreat could not, if the story is to stand as it is written,
have been known to him. It is inconceivable that any sane
commander could possibly have advised the Greeks to attempt
174
operations on the Asian coast at this stage of the war. Again, the
object proposed was manifestly futile. What good could have been
attained by breaking down the bridge, had not a sufficient force been
left behind to maintain the command of the Hellespont against the
Persian fleet? Could not a strait no broader than many parts of the
lower Danube have been easily crossed by means of ship and boat
transport? If the Greek fleet were once entangled in that region,
could the possibility the Persian fleet or of part of it doubling back to
the European coast be ignored? Above all, did
THE
“THEMISTOCLES”
the Greek fleet know whither the enemy had
TRADITION. gone? A very few hours’ start would have
taken them far out of sight. They had had that
start; and all that the Greeks at Andros could have known with
certainty was that there were no ships between that place and
Piræus.
It cannot be doubted that this passage in Herodotus is one of a
series of excerpts from a history of Themistocles composed by a
hostile political party. The tale of the Council at Andros merely
serves the purpose of a peg whereon to found the charge of trickery
or treachery which immediately follows it. The verisimilitude of the
story is to be further supported by knowledge after the event.
Themistocles did in after-time take refuge with the Persians. Was he,
however, likely at the very crowning moment of his life to have
foreseen the eventuality of his being obliged to do so?
The story is so corrupt that it is most difficult to select from it the
element of truth which it may contain. It is possible that a
reconnaissance was made as far as Andros, and that it was decided
to go no farther. It is in the highest degree doubtful whether the tale
of Themistocles’ communication with Xerxes at this time had any
real foundation. The proposal to break down the bridge has all the
appearance of a rechauffé served up with a new sauce, of the story
which connected the hero of the last great battle, Marathon, with the
proposal to break the Danube bridge during Darius’ Scythian
expedition. It has been suggested that he gave the information in all
honesty, because he wished to get Xerxes and his army out of the
way. No doubt he and every other Greek did entertain that wish; but
it is impossible to see how the message, in the form in which it was
H. viii. 110.
sent, could further its fulfilment. The last words of the
message, “Now depart at your leisure,” singularly fail
to accord with the conjectural explanation of Themistocles’ alleged
conduct. There is, at the same time, every possibility that
Themistocles did, after the retreat of the land-army had definitely
begun, urge the advisability of offensive operations on the Asian
coast at some period not long after the battle; and it is probable that
such operations would have been eminently effective. But in this
Themistocles legend these proposals have been purposely
antedated, in order to adduce them as evidence of the truth of
Themistocles’ suspicious communications with Xerxes, before the
latter started on his return journey.
It is quite possible, too, that the rejection of these proposals led to
Themistocles’ resignation of the command of the Athenian fleet. It is
difficult to account for it in any other way. High as party feeling ran at
Athens, the Athenian citizen showed a distinct preference for
entrusting his life amid the chances and changes of war to men of
known capacity, and the Strategia was less affected by the storms of
political contention than the other high departments of government.
Tacked on to this last tale is the story of the siege of Andros. The
Greek fleet, it is said, after renouncing all idea of further pursuit, laid
siege to Andros; “For the Andrians first among the islanders refused
to pay money on Themistocles’ demand; and when Themistocles put
forward the argument that the Athenians had come, having with
them two great gods, Persuasion and Force, so that they would
certainly have to pay, they answered that Athens was naturally great
and prosperous, being blest with such excellent gods, but, as far as
the Andrians were concerned, their land was poor as poor could be,
and two unprofitable gods, Poverty and Inability, left not their island,
but ever abode there; and being cursed with these gods, they were
not going to pay the money; for never could even the power of
Athens be more powerful than their own inability.” So the siege
began.
Themistocles’ demands were not confined to Andros. Large sums
were extorted, under threat of siege, from the islanders, of whom the
Karystians and Parians are named, because they had medized in
the recent war.
The whole language of the story suggests in the plainest possible
way that Themistocles exacted these contributions for his own
benefit. That such demands were made is no
RETREAT OF THE
PERSIAN ARMY.
doubt the case. The bitterness of the feeling
against the medized Greeks might well
suggest that, as a punishment for their crime in taking up arms
against their fellow-countrymen, they should be forced to contribute
to the expenses of the defender of that which they had attacked; but
to represent Themistocles as employing this fleet for his own selfish
ends is plainly a colouring given to the story by the same hand that
invented the previous tale of his relations with Xerxes.
Whatever may be the origin of the Themistocles legend in
Herodotus taken as a whole, this particular section of it was almost
certainly the creation of the aristocratic party, which was, be it said to
its credit, the friend in after days of the subject allies, and therefore,
apart from other political considerations of a more general kind, not
likely to depict in a favourable light the first instance of the imposition
of the island tribute, nor to deal sparingly with the man who might,
with some show of plausibility, be regarded as its originator.
Another important question which suggests itself is whether this
demand on Andros and these exactions from Karystos and Paros
were made at this time, within a few days of Salamis. It is extremely
unlikely that the Greek fleet, with only half of the danger at home
averted, should have ventured at this moment to spend time over the
siege of one of the island towns. The whole incident of the exactions
looks as if it ought to be attributed to a somewhat later date.

H. viii. 113.
The retreat of the Persian army began a few days
after the naval battle. Mardonius accompanied it
because, so Herodotus says, he wished to escort the king. The
campaigning season also was far advanced, and he thought it would
be better to winter in Thessaly. His real motive in retiring so far north,
—a motive Herodotus could hardly appreciate, even if he ever heard
it mentioned,—would be to shorten the line of communications,
especially for commissariat purposes. He had now no fleet upon
which to depend. Moreover, Thessaly was a rich country, whose
local supplies would go far towards satisfying the temporary wants of
his army. There he selected the men who were to remain with him
for the next year’s campaign. He seems to have chosen the best
troops in the huge and motley host, Persians, Medes, Sakæ,
Bactrians and Indians; and Xerxes made no objection. And then the
rest of the helpless throng departed on its long march round the
North Ægean, to carry to Asia a terrible tale of suffering of which but
few details have survived in the Greek historians. According to
Herodotus, three hundred thousand men remained with Mardonius.
It is commonly supposed that this number is largely exaggerated; but
unless there is a proportionate exaggeration in the numbers of the
Greek army present at Platæa, the force which the Persians
opposed to them there can hardly have been less than two hundred
and fifty thousand in number. Mardonius probably retained with him
nearly the whole of the really effective land-force of the original
expedition.

H. viii. 115.
That part of the army which continued its retreat
from Thessaly took forty-five days to reach the
Hellespont. The misery of that time must have been unspeakable,
and but few out of the many ever set foot again on Asian soil. The
realities of a six weeks’ march of four hundred miles, in the case of a
large force wholly unprovided with commissariat, must have been
horrible beyond description. Starving themselves, they spread
famine by their ravages wherever they went. In many places no food
was obtainable, and then they ate the very grass by the way and the
leaves of the trees. Dysentery was the inevitable result. The sick
who fell by the road were left to the care of the natives; and, knowing
the nature of those wild Thracian tribes of the North Ægean, it is not
difficult to imagine that their fate must have been pitiable in the
extreme. At last the survivors reached the Hellespont, to find that the
bridge had been carried away in a storm; but they were transported
to Abydos in boats. Not even then were their misfortunes over. Many
of the starving multitude perished from giving undue satisfaction to
their ravenous hunger.
H. viii. 119.
Herodotus, though he mentions two accounts of the
matter, is of opinion that Xerxes accompanied the
army all through its retreat. He rejects a tale to
AN INTERVAL IN
the effect that on arriving at Eion, at the mouth
THE WAR.
of the Strymon, the king went the rest of the
way by sea on a Phœnician ship, and was only saved from perishing
in a northern gale by the devotion of certain Persians who
accompanied him, and who sacrificed themselves in order to lighten
the ship. Apart from the tale of devotion, the rejected version is
manifestly the more probable. Not to speak of the horrors of the
land-march, the king’s personal safety may well have been imperilled
in the midst of an army which had undergone and was undergoing
the sufferings of his. To Hydarnes was committed the conduct of the
remainder of the retreat.

H. viii. 121.
The siege of Andros turned out a failure. Karystos
was attacked and its territory ravaged; and then a
return was made to Salamis. It is evident that the Greeks themselves
were at this time under the impression that the war in Europe was
over, in so far as they were concerned; and eagerness of the
Athenian section to carry the war into Asia, which Herodotus has
antedated, may be ascribed to this time. The news that Mardonius
had remained in Thessaly, with evident intent to renew the war next
year, can hardly have reached Athens until several weeks at earliest
from the time at which the retreat began.
Under this mistaken impression they began to wind up the skein
of past events, and after their patriotic victory to discuss who had
deserved best of their common fatherland. The gods had been very
good to them, much better, perhaps, than they themselves realized;
and it was to them that their remembrance first turned. To Delphi was
H. viii. 123.
dedicated a tenth of the spoils. After dividing the rest
of the plunder, the Greeks sailed to the Isthmus to
decide by vote who of all of them had rendered the greatest services
to his country in the recent war. The result was unfortunate. Each
general having two votes gave the first to himself, and the majority
gave the second to Themistocles. Under the circumstances they
thought it best to forego the decision; and the various contingents
departed home to their cities.
In spite of this the admiration of Themistocles burst forth, and that
in a most unexpected quarter. He went to Sparta, where such honour
was paid him as never had been previously paid to any foreigner,
and never was again paid up to Herodotus’ own day.
There are certain elements in the political situation at this time
which make it possible that party feeling ran high among the
Plat. Them.
Athenians during the period which now ensued. The
[Arist.] Athen. Areopagus, which still continued to represent all that
Pol. was exclusively aristocratic in Athens and Attica, had
played a considerable part in the measures which had
been taken for the public safety; and if the recently discovered Polity
of Athens, which is attributed to Aristotle, is to be believed, it had
gained considerable reputation thereby. On the other hand, the man
of the hour was Themistocles; and he led political interests directly
opposed to those which the venerable council represented. It may be
that Themistocles’ resignation of the Strategia was not wholly
unconnected with these struggles. He does not appear in history as
a man likely to under-estimate his own personal worth; and the
discovery that, in the turmoil of party strife, the world generally
seemed to set a lower value upon it, may have given bitter offence to
his pride. Herodotus gives no detail of these political events; though
H. viii. 125.
his introduction to a story which he evidently inserts
because it contained such a bon-mot as he dearly
loved, shows that an attack was made on Themistocles immediately
after his return from Sparta. Timodemos of Aphidnæ was the name
of the assailant. He reproached Themistocles with having taken to
himself an honour due to his country; and, apparently, thinking the
175
remark an effective one, repeated it on more than one occasion.
Herodotus, who never discovered a lack of ready wit to be one of
Themistocles’ defects, takes evident pleasure in recording the
crushing retort: “The thing stands thus,” said he; “had I been from
Belbina, I should not have been thus honoured by the Spartans, nor
would you have been, good sir, even had you been from Athens.”
This is the last of the series of events in
THE WAR IN SICILY.
Greece which can be attributed to the year
480, but before proceeding to recount the history of the following
year, it is necessary to recur briefly to what had meanwhile taken
place in Sicily. The brevity of the reference is not due to the
unimportance of the events themselves, but to the meagreness of
the surviving records of them. Herodotus dismisses the subject in a
few words; and the scheme of history which Diodorus had proposed
to himself rendered it impossible for him to devote much space to
them, despite the fact that this year was a most decisive one for the
history of his native land.
After the departure of the Spartan and Athenian ambassadors,
Gelo of Syracuse had been left alone to face that great storm which
Persia had stirred up in the West with the evident intention of
preventing the Sicilian and Italian Greek from taking part in the
defence of the mother country. It was more than fortunate for the
Sicilians that at this most critical moment of their history, such power
as they could put forward was under the control of one strong hand.
The tyrant, or tyrant city, was indeed at all times in Sicilian history
necessary to the salvation of the Greeks, face to face as they were
with the great Carthaginian power in the west of the island,
supported by a central base but a few miles distant across a narrow
sea.
There is no question that the Carthaginian preparations were on a
Diod. xi 20.
very large scale, though the numbers given by
Diodorus are certainly exaggerated. In her struggle
with Rome, more than two centuries later, Carthage, though in all
probability more powerful than she was in 480, could not muster
aught resembling the strength which the Sicilian historian attributes
to her on this occasion. He states the number of the land forces to
have been 300,000. The fleet, he says, consisted of 2000 warships,
together with 3000 transports. It is manifestly useless to attempt
what, in the absence of independent records, can be no more than a
guess as to the actual numbers. All that can be with safety assumed
is that they were very large. The name of the commander was
Hamilcar.
The gods of the winds were hardly less kind to the Greeks of
Sicily than they were to their fellow-countrymen at home. A storm
overtook the expedition in the Libyan sea, and the vessels conveying
the horses and chariots were lost. Hamilcar, however, conducted the
remainder in safety to Panormos. He had no anxiety as to the result
now that he had safely transported the bulk of his forces across the
sea. Doubtless he reckoned on having to deal with a Sicily such as
Sicily had been before the recent rise of Gelo’s power, in which the
great force at his disposal would have been able to crush the Greek
cities in detail.
From Panormos, after repairing, in so far as possible, the damage
suffered in the storm, he marched his army along the coast to
Himera, the fleet keeping in touch with it meanwhile. His method of
advance was consequently similar to that adopted by the Persians in
their march round the Ægean. Arrived at Himera, he formed two
camps, one for the army and one for the fleet. The arrangement of
these camps is interesting, as showing that in the west, as in the
east, the Greeks had to deal with a foe which, whatever his defects,
was both capable and experienced in the organization of large
expeditions over sea. The warships were drawn up on shore and
surrounded by a stockade and deep ditch. The other camp was
contiguous to the naval one, but ran inland to the summit of the
neighbouring heights, to the west of the city of Himera, and facing it.
Hamilcar thus secured his communications with his commissariat
base,—the fleet. The provisions which he had brought with him he
landed, and then despatched the empty transports to Libya and
Sardinia to fetch a further supply. His plan was evidently not to
attempt to assault the town on all sides. The loss of his cavalry
would make it difficult for him to advance far from his sea-base; and,
besides, he had to expect an attack from a relieving force. Having
completed the fortification of his position, he took some of the best of
his soldiers and advanced against the town, whose garrison came
out to meet him, afraid, no doubt, of his establishing siege works in
the immediate neighbourhood of their wall. It had, however, to retire
with severe loss, a disaster which brought the Himerans to a state of
despair. But even thus early in the campaign the town was not wholly
dependent on its own resources. Thero, tyrant of Akragas, who was
content to play a subordinate part to Gelo in
GELO MARCHES TO
RESCUE HIMERA.
Sicilian politics, was either present in it, or,—
for Diodorus’ language is capable of two
interpretations,—in its neighbourhood, with a force whose numbers
are not mentioned. Alarmed at the situation, and evidently not in
sufficient strength to take the offensive against the Carthaginians, he
sent an urgent message to Gelo to come with all speed. Gelo was
ready, and the fact of his being so suggests that the defence against
the invader was being conducted on a definite plan. Syracuse had
evidently been chosen as the base of operations. Its
communications with southern Sicily are both shorter and more easy
than with the north. If the attack took place on the south, which was
probably known to be unlikely, the central force at Syracuse would
be within striking distance. It would seem, therefore, that Thero’s
corps had been sent from the south to the north, where the attack
was more likely to be made, to act as an army of observation, and to
hold the enemy until Gelo could appear with the main army. The plan
was a sound one.

Diod. xi. 21.


The army with which Gelo started from Syracuse is
stated to have numbered 50,000 infantry and 5000
cavalry. He made a rapid march, and his arrival infused new courage
into the Himerans. He did not enter the city, but fortified a camp of
his own outside it, and started active operations by sending out all
the cavalry to cut off Carthaginian stragglers. Hamilcar must have
been at this moment in a position of great disadvantage, owing to the
loss of his horses in the storm. The number of the enemy captured
by this raid of cavalry is stated to have been 10,000; it appears, in
any case, to have been large.
But Gelo had no idea of confining himself to a passive defence of
the place, knowing, in all probability, that the enemy might expect
reinforcements, whereas the Siciliot forces present at Himera
represented the utmost effort of which Sicily was capable. The
Himerans had walled up their city gates. He caused them to be
opened once more, and infused a spirit of cheerful confidence into
the whole Greek army. In all likelihood this change of feeling was
largely due to the comparative inactivity to which Hamilcar was
reduced in face of the large force of Syracusan cavalry against
which, owing to his own loss, he had not any similar force to match.
Something of the kind is indicated by the fact that he sent a message
to Selinus, urgently demanding assistance in this arm. Unluckily for
him, the return messenger announcing its despatch fell into the
hands of Gelo’s men. That able commander had been for some time
devising plans by which he might not merely defeat, but utterly
destroy, the invading army. The intercepting of this message
suggested to him a means of doing so. He had apparently already
made up his mind that an attack on the naval camp, and the
destruction of the ships within it, must be part of his programme. The
disclosure made by the message that the Carthaginians were
expecting cavalry reinforcements suggested to him the design of
substituting cavalry of his own for the looked-for horsemen of
Selinus, so as to obtain access to the naval stockade. It was a bold
plan, but it was entirely successful. Not the least fortunate
circumstance about the matter was that on the very day on which the
cavalry were expected Hamilcar was going to offer a great sacrifice;
and this was apparently known to Gelo. The Syracusan horsemen
were sent under cover of night, and after making a circuit,—the
Greek camp being probably east of the town,—arrived at the naval
camp from the western side just about dawn, and were admitted by
the guards under the impression that they were the Selinuntian
horse. Once inside the stockade, they proceeded immediately to kill
Hamilcar and to set fire to the ships.
But this was only part of the whole plan. Watchers had been
placed upon the heights, with orders to announce by signal the
arrival of the cavalry within the stockade. On receiving the signal,
Gelo, with the whole of the rest of his army, began an assault on the
other Carthaginian camp, which was, as has been seen, situated on
the heights above the naval encampment. The
THE BATTLE OF
HIMERA.
Carthaginian commanders, unaware at first of
what had been going on below them, led out
their men to meet this attack, and for some time the battle was
stubborn and bloody, both sides fighting with great bravery. The
increase of the conflagration in the camp below, however, at last
attracted their notice, and the arrival of a message announcing the
death of Hamilcar completed the dismay of the Carthaginians and
fired the courage of the Greeks. The former gave way, pursued by
the Greeks, to whom orders were given to take no prisoners. Though
the slaughter was a terrible one, it is hardly possible to accept
Diodorus’ statement that one hundred and fifty thousand perished.
Some of the survivors fled to a bare height, where they defied all
direct attack; but they were compelled in the end to capitulate, owing
to there being no water obtainable on the position.
It was a brilliant and crushing victory for the Sicilian Greeks, so
complete and so lasting in its results, that it marked the beginning of
an era of peace and prosperity destined to last for many years.
Diodorus, with a pardonable pride in the exploits of his fellow-
countrymen, draws a comparison between the victory at Himera and
that which the Greeks won at Platæa in the following year. There is
one important point of contrast which he does not mention, but which
will be appreciated by those who are acquainted with the stories of
those two great battles. The resistance which the Carthaginian
troops offered to the Greek hoplite in close fighting was evidently
much more stubborn than that offered by the Persian infantry. It was
not a question of courage; it was not a question of physique. In these
two respects the Persian was probably superior to the Greek, and
not inferior to any contemporary race. The difference was in panoply.
The African and Spaniard wore defensive armour, such as the
Oriental never learnt to use because the climate of the lands wherein
his campaigns were mostly fought rendered the burden of the weight
of it too grievous to be borne. The resistance offered to the Eastern
conqueror took the form of legions of cavalry and mobile bodies of
light-armed infantry, and to meet them he had to employ forces of a
similar kind. Against such, in a land of infinite distances like Western
Asia, an army of hoplites might, if the enemy adopted tactics suitable
to the nature of his force and to the nature of the country, be reduced
to impotence, if not brought to destruction. The campaigns of
Alexander are supposed to have proved the opposite to be the case.
Those who take that view of them seem to forget that the enemy
opposed to him adopted tactics wholly unsuited to the nature of their
army, and fought the very pitched battles which they should have
scrupulously avoided. Had the Persians in that war employed the
tactics which three centuries later led to Carrhæ, the campaigns of
Alexander might have ended in the neighbourhood of the Amanus.
The military history of the East and West in the centuries preceding
the Christian era is ruled by one great limitation. East could not gain
any decisive advantage over West in the West, nor West over East
in the East, unless the enemy made a fundamental error in tactics.
The resources of the East in light cavalry were out of all
proportion to any number of this arm which the West could, even
with the utmost effort, put into the field; and such a force, properly
employed, must have always made the immense plains of the
Euphrates or of Media untraversable to a Western army. In like
manner, against the heavy infantry of the West, accompanied by a
proper quota of light-armed troops, the light infantry of the East were
helpless in regions where it could not be supported by its cavalry;
and west of Taurus, such regions were the rule and not the
exception. The eastern Taurus was, indeed, the military frontier
between East and West.
This generalization may appear to be somewhat wide; but the
results of every single battle in which East and West came into
conflict support it. There are no exceptions. Such cases as appear to
be so afford the strongest evidence of the truth of it: in every one of
them the loser committed some glaring tactical error which robbed
him of the essential advantages which the very nature of things
afforded him.
As a pure example of the military art,
GELO MAKES
PEACE WITH
Himera did more credit to the victors than did
CARTHAGE. Platæa. It was won by reason of a well-devised
plan; Platæa, in spite of an ill-devised one. In
its results it was hardly less decisive, though these results were not
of a character to attract the attention of the modern world so forcibly
as the after-effects of Platæa.
Its actual date in 480 is uncertain. Diodorus assigns it to the same
day as Thermopylæ. Unfortunately, the historians of this period

You might also like