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

JavaScript Design Patterns 1 /

converted Edition Hugo Di Francesco


Visit to download the full and correct content document:
https://textbookfull.com/product/javascript-design-patterns-1-converted-edition-hugo-d
i-francesco/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

MASTERING JAVASCRIPT DESIGN PATTERNS create scalable


and reliable applications with advanced Javascript
design patterns using reliable code 3rd Edition Tomas
Corral Cosas
https://textbookfull.com/product/mastering-javascript-design-
patterns-create-scalable-and-reliable-applications-with-advanced-
javascript-design-patterns-using-reliable-code-3rd-edition-tomas-
corral-cosas/

JavaScript Patterns Build Better Applications with


Coding and Design Patterns 1st Edition Stefanov Stoyan

https://textbookfull.com/product/javascript-patterns-build-
better-applications-with-coding-and-design-patterns-1st-edition-
stefanov-stoyan/

Learning OpenTelemetry 1 / converted Edition Ted Young

https://textbookfull.com/product/learning-
opentelemetry-1-converted-edition-ted-young/

Design Patterns by Tutorials Third Edition Learning


Design Patterns in Swift Raywenderlich Tutorial Team

https://textbookfull.com/product/design-patterns-by-tutorials-
third-edition-learning-design-patterns-in-swift-raywenderlich-
tutorial-team/
Architecting ASP.NET Core Applications: An atypical
design patterns guide for .NET 8, C# 12, and beyond 3rd
Edition (Early Access) Carl-Hugo Marcotte

https://textbookfull.com/product/architecting-asp-net-core-
applications-an-atypical-design-patterns-guide-for-
net-8-c-12-and-beyond-3rd-edition-early-access-carl-hugo-
marcotte/

Design Patterns by Tutorials Learning design patterns


in Swift 4 2 Joshua Greene

https://textbookfull.com/product/design-patterns-by-tutorials-
learning-design-patterns-in-swift-4-2-joshua-greene/

Performance Based Building Design Hugo S. L. Hens

https://textbookfull.com/product/performance-based-building-
design-hugo-s-l-hens/

PowerShell 7 Workshop 1 / converted Edition Nick Parlow

https://textbookfull.com/product/powershell-7-workshop-1-
converted-edition-nick-parlow/

Windows Security Internals 1 / converted Edition James


Forshaw

https://textbookfull.com/product/windows-security-
internals-1-converted-edition-james-forshaw/
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'
);
Another random document with
no related content on Scribd:
DISEASES OF THE SALIVARY GLANDS.
Modifications of the secretion are commonly simple excess or
deficiency, with a correspondingly high or low specific gravity of the
product. There may, however, be a virulent element as in the case of
rabies.
SUPPRESSION OF SALIVARY SECRETION.
XEROSTOMIA.
Causes; fever; vascular vacuity, after bleeding, diarrhœa, etc.; destruction of
glands; Calculus. Symptoms; slow, difficult mastication; digestive disorder.
Treatment; remove mechanical obstruction; correct constitutional disorder;
employ stimulation to gland—pilocarpin, electricity.
Entire suppression of salivary secretion is usually the result of
some other disease. It may be a manifestation of the general
tendency to retain water in the febrile system, or it may be an
indication of vacuity of the vascular system as after bleeding, profuse
diarrhœa, diuresis, or diaphoresis, or it may be the result of the
entire destruction of a salivary gland or the obstruction of its duct by
some foreign body or calculus. In proportion to the completeness of
the suppression, mastication and deglutition become difficult or
impossible. The condition must be met by the removal of the cause
which is operative in the particular case. The treatment may be
surgical for the removal of obstructions, or medical with the view of
overcoming anæmia, fever, profuse secretions from other
emunctories, or the simple physiological inactivity. To meet the last
indication small doses of pilocarpin, or the application of a gentle
current of electricity will usually succeed.
EXCESSIVE SECRETION OF SALIVA.
SALIVATION. PTYALISM.

Causes; a symptom of other diseases, of the mouth, teeth, throat or stomach;


rank aqueous vegetation, lobelia, pilocarpin, muscaria, tobacco, mustard, and
other acrid vegetables; caustic alkalies, acids, salts; compounds of mercury, gold,
copper, iodine; palsy of lips; harsh bit; fungi on clover, sainfoin, etc. Symptoms;
salivary escape; frequent deglutition; thirst; disordered digestion, etc. Treatment;
remove cause; astringent washes; sedatives; embrocations to the glands.

This is often a symptom of some other affection such as aphthous


fever, dumb rabies, epilepsy, stomatitis, pharyngitis, dentition, caries
and other diseases of the teeth, wounds and ulcers of the mouth,
gastric catarrh, etc. In other cases it is due to direct irritants in the
food or medicine, as very rank, aqueous, rapidly grown, spring grass,
lobelia, pilocarpin, muscarin, tobacco, wild mustard, colchicum,
pepper, garlic, ginger, irritant and caustic alkalies, acids and salts,
and the compounds of mercury, gold, copper, or iodine employed
locally or internally. The application of mercurials to the skin is
especially liable to salivate cattle and dogs, partly because of a special
susceptibility to the action of this metal and partly from the tendency
of these animals to lick the medicated surface. Paralysis of the lips
causes a great flow of saliva from the mouth though no more than the
normal amount is secreted. The irritation of a large or harsh bit will
increase the secretion and still more the former habit of attaching to
it small bags of spicy or irritant chemicals. Certain fungi determine
salivation. Mathieu saw profuse salivation in horses, cattle and sheep
fed on clover and sainfoin which had become brown.
Symptoms consist in the profuse flow of saliva, either in long
stringy filaments, or if there is much movement of the jaws, in frothy
masses; frequent deglutition; increased thirst and disordered
digestion (tympany, inappetence, colics, constipation, diarrhœa). In
mercurial salivation there may be loose teeth, swollen, spongy,
ulcerated gums, tympany, rumbling, and the passage of fœtid flatus
and soft ill-digested stools.
Treatment consists in removing the cause, whether this is to be
found in faulty food or drink, diseased teeth or gums, disordered
stomach, or the irritant food medicine or poison ingested. If more is
wanted simple astringent washes like those recommended for
stomatitis and a free access to pure water will often suffice. Tartar
emetic or opium has been known to succeed in obstinate cases.
Friction over the parotid or submaxillary gland with camphorated
spirit, tincture of iodine or soap liniment is sometimes required. In
mercurial salivation chlorate of potash is especially to be
commended, and when the bowels have been unloaded of the agent,
iodide of potassium will hasten its elimination from the tissues and
blood.
DILATED SALIVARY DUCTS. SALIVARY
CALCULUS. SALIVARY FISTULA.
These are all surgical diseases and are to a large extent inter
dependent. The impaction of the calculus in the duct leads to
overdistension of the duct posterior to the obstruction, and the
rupture or incision of the distended duct, determines the fistula. It is
only necessary here to point out the seat of these lesions: the
distended sublingual ducts constituting a more or less rounded
swelling to one side of the frænum lingui, the Whartonian duct
forming a tense rounded cord from the papilla back of the lower
incisor teeth backward on the inner side of the lower jaw, and the
Stenonian duct forming a similar tense cord from near the middle of
the cheek down around the lower border of the jaw in company with
the submaxillary artery and backward on the inner side of its curved
border to the parotid gland.
For the more precise lesions, symptoms and treatment of these,
see a work on surgery.
INFLAMMATION OF THE PAROTID GLAND.
PAROTITIS.

Causes: traumatic; calculus; grains; barley and other beards; infecting microbes.
Symptoms: fever, dullness, buccal heat, salivation, difficult mastication, swelling of
gland and duct, protruded nose, stiff neck, fœtor, dyspnœa, facial paralysis,
induration of gland, abcess. Diagnosis from pharyngitis, abcess of guttural pouch
or pharyngeal glands; from tumors. Treatment: avoidance of causes; derivation;
astringent, antiseptic washes; wet antiseptic bandages to throat; cool pultaceous
diet. Open abscess and disinfect. For induration deobstruents. For sloughing
antiseptics.

This may be caused by traumatism, such as incised punctured or


bruised wounds. Wounds inflicted by the goad, by horns, and even
by the yoke in cattle must be looked on as factors. It occurs from
obstruction of the salivary ducts by calculi, or by grains, seeds, or
pebbles introduced from the mouth; from their irritation by the
beards of barley and other plants (brome, rye, wheat, etc.); and from
the localization in the gland of specific inflammations like strangles,
pyæmia, canine distemper, tuberculosis and pharyngitis. In most of
these cases infective microbes are prominent factors. They enter with
penetrating bodies from the skin; they extend through the weakened
and debilitated tissues in bruises; they penetrate the Stenonian duct
with the various foreign bodies from the mouth; irrespective of
foreign objects they make their way up the duct by continuous
growth from the buccal orifice; in case of calculus or other
obstruction their extension is favored by the local congestion and
debility and by the stagnation of the saliva above the point of arrest.
When present these microbes even favor the deposition of the
salivary salts and formation and increase of calculi so that the
affection may advance in a vicious circle, the microbes favoring
calculus and the calculus favoring the increase of microbes.
Symptoms. In the horse in particular there may be premonitory
symptoms of fever, dullness, heat of the mouth, ptyalism, slow and
imperfect mastication, and the retention of food in the cheeks.
The Stenonian duct becomes swollen and painful. The parotid
becomes hard, hot, tender, and is surrounded by a softer pitting
infiltration which may extend down around the entire throat, and
even along the intermaxillary region to the chin. When the canal is
obstructed it may stand out as a thick rope-like resilient swelling
extending around the lower border of the jaw and upward toward the
cheek as far as the point of obstruction. When one parotid only is
involved, the contrast with the other is quite marked. The head is
extended and carried stiffly. When the nose is depressed, or when
the head is turned to one side or the other, the patient gives evidence
of suffering from compression or stretching of the inflamed region.
The breath and mouth exhale an offensive odor, determined by the
decomposition of mucus and of the retained food products.
Among remote effects may be named dyspnœa and threatened
suffocation from pressure on the pharynx and laryngeal nerves, and
facial paralysis from pressure on the seventh nerve.
The disease may go on to induration and remain permanently in
this condition, or it may suppurate and discharge through the skin,
into the pharynx or through the duct of Stenon. It may communicate
with both the duct and the skin and determine a fistula. When
suppuration occurs there is an access of fever, a chill may be noticed,
the swelling becomes more tense, harder, more tender to the touch,
and even emphysematous, and finally points internally or externally.
This may take place from the fifth to the tenth day or later. When it
opens into the duct it may be seen oozing from the orifice in the
cheek when the mouth is opened, and in case the jaws are suddenly
parted, it may escape in a jet. In such a case and especially if the
microbes have come originally from the food the odor is very fœtid.
The abscess is not always single and when multiple the pus may
escape externally by a variety of orifices. The pus is usually whitish,
yellowish or grayish and creamy, but it may be grumous or bloody or
serous and of a most offensive odor. In exceptional cases the gland
becomes more or less gangrenous and such parts, exposed in the
wound are hard, bloodless and insensible, and add very materially to
the fœtor. This may lead to general septic infection, or the necrosed
masses may slough off and the cavities fill up by granulations.
Diagnosis. Parotitis is distinguished from pharyngitis and abscess
of the guttural pouch by the absence of cough and nasal discharge;
from abscess of the pharyngeal glands it is differentiated by the
limitation of the hard swelling to the parotid gland and by the
superficial seat of the resulting abscess. The co-existence of active
inflammation serves to distinguish it from ordinary tumors.
Treatment. By way of prevention, the avoidance of injuries by
yokes, forks, pokes, and goads is important. Also the disinfection of
the mouth by a liberal supply of pure water and even by antiseptic
washes:—borax, boric acid, creolin, tannin, chlorate of potash. Also
by the removal of foreign bodies or calculi from the canal.
When the inflammation has set in, a saline laxative is often of
value. Wash the mouth with a solution of vinegar and salt, or other
antiseptic, repeating this at least after every meal. The swollen,
painful gland may be covered with a damp compress or anointed
with vaseline to which may be added a little creolin, naphthol,
carbolic acid or salicylic acid, together with lead acetate and
belladonna or other anodyne. The diet must be soft, cool mashes,
sliced or pulped roots or any bland agent that will demand little or no
mastication. Cool, fresh water should be allowed ad libitum. When
the laxative has set, it may be followed by cooling diuretics such as
nitrate or acetate of potash.
If suppuration occurs it should be opened as soon as the pus can
be definitely recognized, and the cavity treated antiseptically to
prevent further local or general infection by the microbes. In deep
abscess there is a certain danger of wounding blood vessels and
salivary ducts, but this can be to a certain extent obviated by making
an incision through the skin only and then boring the way into the
abscess with a grooved director or the points of closed scissors.
When the cavity is penetrated the pus will ooze out through the
groove or between the scissor blades. When the pus has been
evacuated the cavity should be washed out two or three times a day
with mercuric chloride solution (1 : 1000), or permanganate of
potash solution (1 : 100).
When the gland becomes indurated and indolent seeming to
merge into the chronic form it may be stimulated to a healthier
action by a cantharides blister, or it may be subjected to daily
massage, or to a daily current of electricity for ten or fifteen minutes.
If the inflammation is slight or unrecognizable, the surface of the
gland may be daily painted with tincture of iodine, and iodide of
potassium maybe given internally, in daily doses of ½ to 1 drachm.
Gangrene, the result of septic microbes, a weak system or too
severe treatment, may be met by astringent and antiseptic agents
locally, and by tonics, stimulants and a generous diet internally.
In cattle the disease usually responds readily to local antiseptics,
and stimulating germicidal embrocations. Camphorated spirit, alone
or combined with tincture of iodine; cantharides ointment with
carbolic acid; and camphor and phenol may be cited as examples.
SUB MAXILLARY ADENITIS. MAXILLITIS.
Mostly in solipeds and unilateral. Causes; traumatic; calculus; infections;
ablation of papillæ. Symptoms; tardy mastication; salivation; buccal heat and
fœtor; submaxillary swelling and tenderness; morsels retained under tongue;
papilla and duct swollen, tender and firm; abscess. Treatment; remove causes;
dislodge foreign bodies; antiseptic lotions and packing.
This is rarely seen in other animals than solipeds, is mostly
unilateral, and due to the introduction of microbes along with
vegetable spikes (barley awns, brome, wheat or oat spikes or glumes)
or other foreign bodies. It may also be caused by calculi obstructing
the duct. The orifice of each duct, to one side of the frænum lingui, is
imperfectly closed by a triangular valvular projection, which in some
countries is erroneously cut off as a diseased product (barbs), thus
opening the way for the introduction of foreign objects. The microbes
are usually pus germs and tend to abscess of the gland. As in the case
of the Stenonian duct the presence of these germs tends to the
precipitation of the salivary salts and the formation of calculi.
Symptoms. The animal may seem hungry, but masticates tardily
and imperfectly, and may even drop morsels partly chewed. He
prefers ground feed to whole, and soft mashes to ground feed, while
hay and other fibrous aliments may be altogether rejected. Salivation
may be excessive, the secretion drivelling from the lips, the mouth
may feel hot and the submaxillary salivary gland swollen and tender.
This may be detected in the intermaxillary space, but is especially
noticeable along the lower and lateral aspect of the tongue. If the
mouth is opened and the tongue drawn to one side a mass of food
may be found to one side of the frænum lingui, and beneath this the
projecting, red inflamed papilla which covers the Whartonian orifice.
Extending backward from this the duct is felt as a thickened cord,
and when this is compressed a purulent liquid flows from the orifice.
The mouth becomes offensively fœtid.
The tendency is to suppuration, and if this is determined in the
Whartonian duct only, by the presence of foreign bodies, calculi, or
microbes it may recover in connection with an abundant muco
purulent discharge and a free secretion of saliva. If it occurs in the
gland tissue itself by reason of the penetration of the microbes into
the follicles, the tendency is to circumscribed abscess, which may
point and burst by the side of the root of the tongue, or externally in
the intermaxillary space. In the first case the tongue is displaced
upward and to the other side of the mouth by the hard, firm swelling,
which is felt on one side beneath the back part of that organ, and
later there is the wound, the profuse muco purulent discharge, and
intense fœtor. If on the other hand the abscess forms nearer the skin,
there is the firm, painful intermaxillary swelling, which finally points
and bursts discharging pus of a septic odor. It may be mixed with the
foreign bodies that have penetrated through the canal, with morsels
of necrosed gland tissue and with blood.
Treatment. The first consideration is to extract any foreign bodies
which have lodged in the duct causing irritation and infection. The
finger passed along the line of the swollen duct may detect the seat of
such foreign body by the extra swelling, and may extract it by
manipulation from behind forward. This may sometimes be assisted
by the introduction of a grooved director as far as the foreign body,
or even by a catheter which can be made to distend the canal in front
of the object and open the way for its easier passage. In case of
failure and in all cases of the introduction of small bodies like
vegetable awns or spikes pilocarpin may be given to cause an
excessive secretion and thus as it were purge the canal of its offensive
contents. Incision of the canal over the foreign body is the dernier
resort.
This accomplished, the injection of antiseptic solutions
(permanganate of potash, boric acid), and the liberal use of pure
water and detergent lotions in the mouth (vinegar, borax, carbolic
acid or salicylic acid in solution) will go far to establish a cure. In
case of an abscess bursting internally the antiseptic solutions should
be injected into its cavity. When the abscess bursts externally this is
doubly demanded, as the introduction of aerial germs tends to
produce very unhealthy action. The cavity may be stuffed with
carbolized, or iodoform, or acetanilid cotton, or with boric or salicylic
acid.
SURGICAL LESIONS OF THE SALIVARY
GLANDS.
Among these may be named calculi of the Stenonian and
Whartonian ducts, ranula, stenosis and fistulæ of these ducts,
tumors, special infections like actinomycosis.
TONSILITIS IN PIGS, AND OTHER
ANIMALS.
Causes; debilitating, climatic, microbian. Symptoms; fever, dullness; lies under
litter; ears and tail droop; watery eyes; anorexia; vomiting; pharyngeal swelling;
buccal redness and fœtor; tonsils swollen with pus or caseous mass in follicles;
cough dry and hard, later loose. Abscess. Calculus. Course. Treatment; antiseptic
electuaries; embrocations; laxatives; diuretics; tonics.
This is seen in both the acute and chronic form. In the former it
has the general causes and symptoms of pharyngitis. There is more
or less fever, dullness, a disposition to lie with head extended and
buried in the litter, ears drooping, eyes watering and red,
carelessness of food, deglutition painful, and liable to be followed by
vomiting. The mouth is red and hot, the breath fœtid and the tonsils
swollen, and their alveoli filled with muco purulent matter or at
times with a fœtid cheese-like product. The cough is at first dry and
hard and later loose and gurgling.
In the chronic form there is general swelling of the tonsils with the
overdistension of the follicles by the above mentioned whitish putty-
like masses, which are often even calcareous. These are due to the
proliferation of microbes which find in these alveoli a most favorable
field for their propagation. A similar condition is found in the
carnivora and to a less extent in the horse, in keeping with the
restricted development of the amygdalæ in these animals. It may be
attended by ulceration, or in rare cases by the formation of veritable
calculi in the follicles of the tonsils.
The gravity of the disease is largely determined by the nature of
the infecting microbe and the debility and susceptibility of the
animal attacked. The affection usually ends in recovery, but may go
on to grave local ulceration, and general infection.
Treatment consists largely in astringent and antiseptic
applications to the buccal mucous membrane. In the acute forms
frequent smearing of the mouth with electuaries of honey or
molasses and borax, boric acid, salammoniac, chlorate or
permanganate of potash, and the application of stimulating
embrocations to the skin around the throat. In other cases solutions
of tincture of chloride of iron, or of tincture of iodine can be used
with profit. The iron can be swallowed with advantage, but it is
objectionable to pour liquid rapidly into the mouth of the pig,
because of the danger of its entering the lungs and setting up fatal
pneumonia. A better way is to apply it to the interior of the mouth
and fauces on a swab or sponge dipped in the liquid. Short of this
one of these agents may be mixed with the drinking water, or
muriatic acid may be used in the same way, though at some
detriment to the teeth. The general health must at all times be
attended to. Any costiveness may be corrected by Glauber salts or
jalap, and elimination through the kidneys must be sought through
the use of nitrate of potash or other diuretic.
CALCULI IN THE TONSILS.

Diagnosis and treatment of tonsillar calculi; spud; acid dressings. Trauma of soft
palate by stick, probang, file, molar. Abscess of palate. Treatment; laxative;
expectorant; antiseptic; lancing. Cleft palate and hare lip.

Rudimentary as these organs are in the equine race they are


important enough to have become the seat of hard calculous masses.
These have been found by Goubaux and Blanc in old asses, and by
the author in old horses. They vary in size from a pin’s head to a pea
and consist of concentric layers of a granular material arranged
around a central nucleus, which is usually a foreign body introduced
with the food. This nucleus is usually of a vegetable nature, while the
enveloping material is made up largely of the imprisoned and
degenerated epithelium of the follicle. Both diagnosis and treatment
are difficult in such cases. The adventitious masses should be
dislodged by the aid of a smooth, blunt metallic spud, and the surface
thereafter washed or swabbed with an antiseptic and astringent
solution. Swabbing with a solution of hydrochloric acid will tend to
dissolve and remove them.
INJURIES TO THE SOFT PALATE AND
FAUCES.
The region of the fauces is sometimes injured by sharp pointed
bodies swallowed in the food, by the giving of boluses on the end of a
pointed stick, or by the careless use of a probang or of a file upon the
posterior molars. An overgrown last molar will sometimes lacerate
the velum. In other cases the inflammation of sore throat is
especially concentrated on this part, giving rise to cough, difficulty of
swallowing, redness, infiltration and swelling of the parts, and even
abscess. In the dog it is often associated with tonsilitis.
Treatment. A laxative is usually desirable to be followed by
salammoniac or chlorate of potash. In case of actual traumatic
lesions, the astringent and antiseptic lotions advised for tonsilitis will
be in order, and if abscess is recognized it should be opened
promptly.
CLEFT PALATE.
In exceptional cases the soft palate has failed to unite in the
median line, and is represented by two lateral flaps separated by a v-
shaped hiatus in the middle. In a specimen in the N. Y. S. V. College,
taken from a trotting colt, the fissure is continued forward for several
inches between the palatine bones and the palatine processes of the
superior maxillary, establishing a direct communication between the
mouth and nasal chambers. In still other instances the fissure is
continued forward between the maxillary and anterior maxillary
bones, throwing the whole length of the buccal and nasal chambers
into one irregular cavity, and forming harelip.
It would be possible to remedy some of these conditions by plastic
operation, but the value of the young animal will rarely warrant any
such resort.
CATARRHAL PHARYNGITIS.
Causes: traumatic; thermic; gaseous; medicinal; chemical; physiological
irritants; in solipeds, cattle, swine, dogs; debility; exposure; cold baths; youth; age.
Microbes in solipeds, cattle, dogs, birds; facultative microbes. Symptoms:
constitutional; difficult swallowing; nasal rejection of water; pharyngeal swelling
and tenderness; extended head carried stiffly; cough loose; salivation; in cattle,
grinding of teeth; in dogs, rubbing of chops; buccal heat and redness; often fœtor.
Course. Duration. Diagnosis from parotitis, from abscess of guttural pouch, from
pharyngeal tuberculosis, from actinomycosis, from adenitis and phlegmonous
pharyngitis, from specific fevers affecting the pharynx. Lesions: redness and
swelling of mucosa, epithelial degeneration, elevations, erosions, and ulcers;
lesions of tubercle, glanders, rabies, anthrax, actinomycosis, etc. Prevention.
Treatment: soothing; dietetic; laxative; expectorant; eliminating; locally antiseptic
astringents in solid, liquid, or vapor; embrocations and blisters; tonics.
Causes. As in stomatitis the starting point of pharyngitis is usually
in a local injury or a systemic condition which lowers the vitality of
the pharyngeal mucous membrane. It may come in all animals from
the hot air of burning buildings, from acrid gases inhaled, food, drink
or medicines given at too high a temperature, from caustic alkalies,
acids or salts, from physiological irritants like croton, euphorbium,
cantharides, from barley and other spikes entangled in the follicles,
from drinking freely of iced water. In solipedes there are the injuries
caused by giving boluses on pointed sticks, and the wounds caused
by tooth files in careless hands, and by coarse fibrous fodder, which
has been swallowed without due mastication. In cattle injury comes
from foreign bodies impacted, from the rough use of probang, rope
or whip and even of the hands in relieving choking. Swine have the
part scratched and injured by rough or pointed objects which they
bolt carelessly with the food. Dogs and especially puppies are often
hurt by solid and irritant bodies that they play with, and swallow
accidentally or wantonly. They also suffer at times from the pressure
of a tight or badly adjusted collar.
The system is debilitated and rendered more susceptible by chills
consequent on exposure to cold blasts, or draughts, or rain or snow,
when heated and exhausted, by cold damp beds, by pre-existing
disease, by underfeeding and by overwork. In the larger animals this
may come from the excessive ingestion of iced water, while in dogs
the plunging in rivers, ponds or lakes may chill.
The weakness of early age and old age have a perceptible
predisposing influence especially in solipeds and carnivora.
Finally as in other catarrhal inflammations the local action of
disease germs on the mucous membrane must ever be borne in
mind. These may be the germs of specific diseases localized in the
pharynx;—in Solipeds the streptococcus of strangles, the bacillus of
glanders, the diplococcus (streptococcus) of contagious pneumonia,
the germ of influenza, and actinomyces;—in Cattle the bacillus
tuberculosis, the bacillus of anthrax, actinomyces, the germs of
aphthous fever and of pseudomembranous angina; in dogs canine
madness and distemper;—in birds the bacillus of
pseudomembranous pharyngitis.
In addition to such specific germs the micrococci, streptococci and
bacilli which are normally present and harmless in the mouth and
pharynx, enter, colonize and irritate the debilitated tissues in case of
trauma, inflammation or constitutional disorder and serve to
perpetuate and aggravate the affection.
Symptoms. Acute pharyngitis is manifested by impaired or lost
appetite, dullness, weakness, by difficulty in deglutition, by the
rejection through the nose of water or other liquids swallowed, by
swelling over the parotid and above the larynx, and by a disposition
to keep the head extended on the neck and the nose raised and
protruded. Fever is more or less marked according to the severity of
the attack the temperature being raised in mild cases to 100°, and, in
the more violent, to 104° or 106°. The pulse and breathing may be
excited, amounting sometimes to dyspnœa, the throat is tender to
the touch and its manipulation rouses a cough, the nasal mucosa is
congested and the buccal membrane, and especially along the
margin of the tongue may be red and angry. Salivation is shown
more or less, in solipeds the saliva accumulating especially during
mastication in froth and bubbles at the commissures of the mouth,
while in ruminants the grinding of the teeth or frequent movement
of the jaws in the absence of food or actual mastication leads to a free
escape of the filmy liquid at the same points. Dogs will rub the jaws
with the foot as if to remove some irritating object from the mouth.
In the last named animals the swelling of the tonsils, fauces and
pharyngeal mucous membrane, may be seen marked by patches and
spots of varying redness and swelling, covered with glairy or opaque
mucopurulent secretions, or particles of food, or even showing
erosions.
The cough of pharyngitis is painful, paroxysmal, and softer and
more gurgling (even in the early stages) than that of laryngitis or
bronchitis. It is roused by handling the throat, by swallowing, by a
draught of cold air or by passing out of doors, in dogs by opening the
mouth, and in cattle by pulling on the tongue which causes pain and
resistance. The cough is followed by the rejection, mainly through
the nose in solipeds, but also through the mouth in other animals, of
a glairy mucus or an opaque mucopurulent discharge often mixed
with and discolored by the elements of food or in bad cases by blood.
The course of the disease is comparatively rapid, and it usually
ends in recovery in seven to fifteen days, in cases that are not
complicated by dangerous local infections.
Diagnosis is mainly based on the stiff carriage of the neck with the
nose elevated, the swelling and tenderness of the throat,
manipulation above the larynx rousing the cough, the soft or rattling
nature of the cough, the ejection of liquids and foods through the
nose, the movements of the jaws apart from mastication and the
salivation. From parotitis it is distinguished by the concentration of
the swelling and tenderness to the deepseated region above the
larynx, by the abundance of the discharge, by the ejection of liquids
through the nose, and by the readiness with which the cough is
aroused. From abscess of the guttural pouch it is differentiated by
the more continuous discharge from the nose, rather than the
intermittent one. From tuberculous pharyngeal glands by its acute
nature, by the absence of the glandular swellings in which the
tuberculosis is concentrated, also by the absence of tubercles in other
parts of the body. From actinomycosis by its more rapid progress
and by the absence of the hard indurated cutaneous or subcutaneous
swellings, and of the open sores with minute sulphur colored
granules that mark that affection. From adenitis and phlegmonous
pharyngitis it is distinguished by the absence of the glandular
swelling and dyspnœa which attend on that affection. From the
various fatal febrile affections, the germs of which may be localized
in the throat, it may be diagnosed by the absence of the more

You might also like