The principles of object oriented JavaScript Zakas - Instantly access the full ebook content in just a few seconds
The principles of object oriented JavaScript Zakas - Instantly access the full ebook content in just a few seconds
com
https://ebookgate.com/product/the-principles-of-object-
oriented-javascript-zakas/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/object-oriented-oracle-wenny-rahayu/
ebookgate.com
https://ebookgate.com/product/management-of-the-object-oriented-
development-process-1st-edition-liping-liu/
ebookgate.com
https://ebookgate.com/product/php-object-oriented-solutions-1st-
edition-david-powers/
ebookgate.com
https://ebookgate.com/product/object-oriented-programming-
with-c-2-e-second-edition-sahay/
ebookgate.com
https://ebookgate.com/product/object-oriented-design-and-patterns-2nd-
edition-cay-s-horstmann/
ebookgate.com
https://ebookgate.com/product/object-oriented-programming-with-abap-
objects-1st-edition-james-wood/
ebookgate.com
https://ebookgate.com/product/object-oriented-programming-in-c-7th-
print-with-corrections-edition-lafore/
ebookgate.com
TAKE
CONTROL OF Foreword by Cody Lindley,
T H E PR
P R IN CIPL
CIP L ES OF
Best-selling Author and
JAVASCRIPT Principal Frontend Architect
O B J ECT -O R I EN T ED
T H E F I N E ST I N G E E K E N T E RTA I N M E N T ™
w w w.nostarch.com
ZA K A S
SFI-00
The Principles of
Object-Oriented JavaScript
T h e P r i n cipl es of
Object-Oriented
JavaScript
by Nicholas C. Zakas
San Francisco
THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT. Copyright © 2014 by Nicholas C. Zakas.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the
prior written permission of the copyright owner and the publisher.
Printed in USA
First printing
18 17 16 15 14 1 2 3 4 5 6 7 8 9
ISBN-10: 1-59327-540-4
ISBN-13: 978-1-59327-540-2
For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly:
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and
company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark
symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to
the benefit of the trademark owner, with no intention of infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been
taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any
person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the infor-
mation contained in it.
About the Author
Nicholas C. Zakas is a software engineer at Box and is known for w riting
on and speaking about the latest in JavaScript best practices. He honed
his experience during his five years at Yahoo!, where he was principal
frontend engineer for the Yahoo! home page. He is the author of sev-
eral books, including Maintainable JavaScript (O’Reilly Media, 2012)
and Professional JavaScript for Web Developers (Wrox, 2012).
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Chapter 2: Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Chapter 5: Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Conte nt s in De ta il
Acknowledgments xv
Introduction xvii
Who This Book Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xviii
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Help and Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
1
Primitive and Reference Types 1
What Are Types? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Primitive Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Identifying Primitive Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Primitive Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Creating Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Dereferencing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Adding or Removing Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Instantiating Built-in Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Literal Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Object and Array Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Function Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Regular Expression Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Property Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Identifying Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Identifying Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Primitive Wrapper Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2
Functions 17
Declarations vs. Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Functions as Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Object Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
The this Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Changing this . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3
Understanding Objects 31
Defining Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Detecting Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Removing Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Types of Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Property Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Common Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Data Property Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Accessor Property Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Defining Multiple Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Retrieving Property Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Preventing Object Modification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Preventing Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Sealing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Freezing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4
Constructors and Prototypes 49
Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
The [[Prototype]] Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using Prototypes with Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Changing Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Built-in Object Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5
Inheritance 65
Prototype Chaining and Object.prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Methods Inherited from Object.prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Modifying Object.prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Object Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Constructor Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
x Contents in Detail
Constructor Stealing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Accessing Supertype Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6
Object Patterns 79
Private and Privileged Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
The Module Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Private Members for Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Scope-Safe Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Index 93
Contents in Detail xi
Fore word
xiv Foreword
Acknowledgments
xviii Introduction
other languages is a strong indicator that this book is for you. In particu-
lar, this book is aimed at three groups of readers:
This book is not for beginners who have never written JavaScript. You
will need a good understanding of how to write and execute JavaScript
code to follow along.
Overview
Chapter 1: Primitive and Reference Types introduces the two different
value types in JavaScript: primitive and reference. You’ll learn what distin-
guishes them from each other and how understanding their differences
is important to an overall understanding of JavaScript.
Chapter 2: Functions explains the ins and outs of functions in
JavaScript. First-class functions are what makes JavaScript such an inter-
esting language.
Chapter 3: Understanding Objects details the makeup of objects in
JavaScript. JavaScript objects behave differently than objects in other lan-
guages, so a deep understanding of how objects work is vital to mastering
the language.
Chapter 4: Constructors and Prototypes expands on the previous
discussion of functions by looking more specifically at constructors. All
constructors are functions, but they are used a little bit differently. This
chapter explores the differences while also talking about creating your
own custom types.
Chapter 5: Inheritance explains how inheritance is accomplished
in JavaScript. Though there are no classes in JavaScript, that doesn’t
mean inheritance isn’t possible. In this chapter, you’ll learn about proto-
typal inheritance and how it differs from class-based inheritance.
Chapter 6: Object Patterns walks through common object pat-
terns. There are many different ways to build and compose objects in
JavaScript, and this chapter introduces you to the most popular patterns
for doing so.
Introduction xix
Primitive and
1
Reference T ypes
2 Chapter 1
Primitive Types
Primitive types represent simple pieces of data that are stored as is, such
as true and 25. There are five primitive types in JavaScript:
Boolean true or false
Number Any integer or floating-point numeric value
String A character or sequence of characters delimited
by either single or double quotes (JavaScript has no
separate character type)
Null A primitive type that has only one value, null
Undefined A primitive type that has only one value, undefined
(undefined is the value assigned to a variable that is not
initialized)
The first three types (Boolean, number, and string) behave in similar
ways, while the last two (null and undefined) work a bit differently, as will
be discussed throughout this chapter. All primitive types have literal rep-
resentations of their values. Literals represent values that aren’t stored in a
variable, such as a hardcoded name or price. Here are some examples of
each type using its literal form:
// strings
var name = "Nicholas";
var selection = "a";
// numbers
var count = 25;
var cost = 1.51;
// boolean
var found = true;
// null
var object = null;
// undefined
var flag = undefined;
var ref; // assigned undefined automatically
console.log(color1); // "red"
console.log(color2); // "red"
color1 = "blue";
console.log(color1); // "blue"
console.log(color2); // "red"
In this code, color1 is changed to "blue" and color2 retains its original
value of "red".
4 Chapter 1
As you might expect, typeof returns "string" when the value is a string;
"number" when the value is a number (regardless of integer or floating-
point values); "boolean" when the value is a Boolean; and "undefined" when
the value is undefined.
The tricky part involves null.
You wouldn’t be the first developer to be confused by the result
of this line of code:
When you run typeof null, the result is "object". But why an object
when the type is null? (In fact, this has been acknowledged as an error by
TC39, the committee that designs and maintains JavaScript. You could
reason that null is an empty object pointer, making "object" a logical
return value, but that’s still confusing.)
The best way to determine if a value is null is to compare it against
null directly, like this:
Notice that this code uses the triple equals operator (===) instead of the double
equals operator. The reason is that triple equals does the comparison without
coercing the variable to another type. To understand why this is important,
consider the following:
When you use the double equals, the string "5" and the number 5
are considered equal because the double equals converts the string into a
number before it makes the comparison. The triple equals operator doesn’t
consider these values equal because they are two different types. Likewise,
when you compare undefined and null, the double equals says that they are
equivalent, while the triple equals says they are not. When you’re trying to
identify null, use triple equals so that you can correctly identify the type.
NO T E Despite the fact that they have methods, primitive values themselves are not objects.
JavaScript makes them look like objects to provide a consistent experience in the
language, as you’ll see later in this chapter.
Reference Types
Reference types represent objects in JavaScript and are the closest things
to classes that you will find in the language. Reference values are instances
of reference types and are synonymous with objects (the rest of this chap-
ter refers to reference values simply as objects). An object is an unordered
list of properties consisting of a name (always a string) and a value. When
the value of a property is a function, it is called a method. Functions them-
selves are actually reference values in JavaScript, so there’s little differ-
ence between a property that contains an array and one that contains a
function except that a function can be executed.
Of course, you must create objects before you can begin working
with them.
Creating Objects
It sometimes helps to think of JavaScript
Object
objects as nothing more than hash tables,
as shown in Figure 1-2.
There are a couple of ways to c reate, name value
or instantiate, objects. The first is to use
the new operator with a constructor. (A con- name value
structor is simply a function that uses new
to create an object—any function can be Figure 1-2: Structure of an object
6 Chapter 1
a constructor.) By convention, constructors in JavaScript begin with a
capital letter to distinguish them from nonconstructor functions. For
example, this code instantiates a generic object and stores a reference
to it in object:
Reference types do not store the object directly into the variable to
which it is assigned, so the object variable in this example doesn’t actually
contain the object instance. Instead, it holds a pointer (or reference) to
the location in memory where the object exists. This is the primary dif-
ference between objects and primitive values, as the primitive is stored
directly in the variable.
When you assign an object to a variable, you’re actually assigning a
pointer. That means if you assign one variable to another, each variable
gets a copy of the pointer, and both still reference the same object in
memory. For example:
This code first creates an object (with new) and stores a reference in
object1. Next, object2 is assigned the value of object1. There is still only
the one instance of the object that was created on the first line, but both
variables now point to that object, as illustrated in Figure 1-3.
Memory
Variable Object
object1
Object
object1
Dereferencing Objects
JavaScript is a garbage-collected language, so you don’t really need to
worry about memory allocations when you use reference types. However,
it’s best to dereference objects that you no longer need so that the garbage
collector can free up that memory. The best way to do this is to set the
object variable to null.
// do something
Here, object1 is created and used before finally being set to null.
When there are no more references to an object in memory, the gar-
bage collector can use that memory for something else. (Dereferencing
objects is especially important in very large applications that use millions
of objects.)
object1.myCustomProperty = "Awesome!";
console.log(object2.myCustomProperty); // "Awesome!"
NO T E This example demonstrates one particularly unique aspect of JavaScript: You can
modify objects whenever you want, even if you didn’t define them in the first place.
And there are ways to prevent such modifications, as you’ll learn later in this book.
8 Chapter 1
Error A runtime error (there are also several more specific
error subtypes)
Function A function
Object A generic object
RegExp A regular expression
You can instantiate each built-in reference type using new, as
shown here:
Literal Forms
Several built-in reference types have literal forms. A literal is syntax that
allows you to define a reference value without explicitly creating an object,
using the new operator and the object’s constructor. (Earlier in this chap-
ter, you saw examples of primitive literals including string literals, numeric
literals, Boolean literals, the null literal, and the undefined literal.)
var book = {
name: "The Principles of Object-Oriented JavaScript",
year: 2014
};
You can also use string literals as property names, which is use-
ful when you want a property name to have spaces or other special
characters:
var book = {
"name": "The Principles of Object-Oriented JavaScript",
"year": 2014
};
NO T E Using an object literal doesn’t actually call new Object(). Instead, the JavaScript
engine follows the same steps it does when using new Object() without actually
calling the constructor. This is true for all reference literals.
You can define an array literal in a similar way by enclosing any num-
ber of comma-separated values inside square brackets. For example:
Function Literals
You almost always define functions using their literal form. In fact, using
the Function constructor is typically discouraged given the challenges of
maintaining, reading, and debugging a string of code rather than actual
code, so you’ll rarely see it in code.
Creating functions is much easier and less error prone when you use
the literal form. For example:
function reflect(value) {
return value;
}
// is the same as
This code defines the reflect() function, which returns any value
passed to it. Even in the case of this simple function, the literal form is
easier to write and understand than the constructor form. Further, there
10 Chapter 1
is no good way to debug functions that are created in the constructor
form: These functions aren’t recognized by JavaScript debuggers and
therefore act as a black box in your application.
// is the same as
Property Access
Properties are name/value pairs that are stored on an object. Dot nota-
tion is the most common way to access properties in JavaScript (as in
many object-oriented languages), but you can also access properties on
JavaScript objects by using bracket notation with a string.
For example, you could write this code, which uses dot notation:
function reflect(value) {
return value;
}
Other reference types are trickier to identify because, for all reference
types other than functions, typeof returns "object". That’s not very help-
ful when you’re dealing with a lot of different types. To identify reference
types more easily, you can use JavaScript’s instanceof operator.
The instanceof operator takes an object and a constructor as param-
eters. When the value is an instance of the type that the constructor speci-
fies, instanceof returns true; otherwise, it returns false, as you can see here:
function reflect(value) {
return value;
}
12 Chapter 1
In this example, several values are tested using instanceof and a con-
structor. Each reference type is correctly identified by using instanceof
and the constructor that represents its true type (even though the con-
structor wasn’t used in creating the variable).
The instanceof operator can identify inherited types. That means
every object is actually an instance of Object because every reference type
inherits from Object.
To demonstrate, the following listing examines the three references
previously created with instanceof:
function reflect(value) {
return value;
}
Identifying Arrays
Although instanceof can identify arrays, there is one exception that affects
web developers: JavaScript values can be passed back and forth between
frames in the same web page. This becomes a problem only when you try
to identify the type of a reference value, because each web page has its
own global context—its own version of Object, Array, and all other built-
in types. As a result, when you pass an array from one frame to another,
instanceof doesn’t work because the array is actually an instance of Array
from a different frame.
To solve this problem, ECMAScript 5 introduced Array.isArray(),
which definitively identifies the value as an instance of Array regardless
of the value’s origin. This method should return true when it receives
a value that is a native array from any context. If your environment is
ECMAScript 5 compliant, Array.isArray() is the best way to identify arrays:
console.log(Array.isArray(items)); // true
console.log(name.last); // undefined
This code attempts to add the property last to the string name. The
code itself is just fine except that the property disappears. What happened?
When working with regular objects, you can add properties at any time
and they stay until you manually remove them. With primitive wrapper
types, properties seem to disappear because the object on which the
property was assigned is destroyed immediately afterward.
14 Chapter 1
Here’s what’s actually happening in the JavaScript engine:
if (found) {
console.log("Found"); // this executes
}
Summary
While JavaScript doesn’t have classes, it does have types. Each variable
or piece of data is associated with a specific primitive or reference type.
The five primitive types (strings, numbers, Booleans, null, and undefined)
represent simple values stored directly in the variable object for a given
context. You can use typeof to identify primitive types with the exception
of null, which must be compared directly against the special value null.
Reference types are the closest thing to classes in JavaScript, and
objects are instances of reference types. You can create new objects
using the new operator or a reference literal. You access properties and
methods primarily using dot notation, but you can also use bracket nota-
tion. Functions are objects in JavaScript, and you can identify them with
the typeof operator. You should use instanceof with a constructor to iden-
tify objects of any other reference type.
To make primitives seem more like references, JavaScript has three
primitive wrapper types: String, Number, and Boolean. JavaScript creates
these objects behind the scenes so that you can treat primitives like
regular objects, but the temporary objects are destroyed as soon as the
statement using them is complete. Although you can create your own
instances of primitive wrappers, it’s best not to do that because it can
be confusing.
16 Chapter 1
2
Functions
This code actually assigns a function value to the variable add. The
function expression is almost identical to the function declaration except
for the missing name and the semicolon at the end. Assignment expres-
sions typically end with a semicolon, just as if you were assigning any
other value.
Although these two forms are quite similar, they differ in a very impor-
tant way. Function declarations are hoisted to the top of the context (either
the function in which the declaration occurs or the global scope) when the
code is executed. That means you can actually define a function after it is
used in code without generating an error. For example:
18 Chapter 2
This code might look like it will cause an error, but it works just fine.
That’s because the JavaScript engine hoists the function declaration to
the top and actually executes the code as if it were written like this:
// error!
var result = add(5, 5);
As long as you always define functions before using them, you can use
either function declarations or function expressions.
Functions as Values
Because JavaScript has first-class functions, you can use them just as
you do any other objects. You can assign them to variables, add them
to objects, pass them to other functions as arguments, and return them
from functions. Basically, you can use a function anywhere you would
use any other reference value. This makes JavaScript functions incredibly
powerful. Consider the following example:
u function sayHi() {
console.log("Hi!");
}
Functions 19
In this code, there is a function declaration for sayHi u. A variable
named sayHi2 is then created and assigned the value of sayHi v. Both sayHi
and sayHi2 are now pointing to the same function, and that means either
can be executed, with the same result. To understand why this happens,
take a look at the same code rewritten to use the Function constructor:
v numbers.sort();
console.log(numbers); // "[1, 10, 2, 4, 5, 6, 7, 8]"
20 Chapter 2
Compare that to the second call to sort() v, which does not use a
comparison function. The order of the array is different than expected,
as 1 is followed by 10. This is because the default comparison converts all
values to strings before comparing them.
Parameters
Another unique aspect of JavaScript functions is that you can pass any
number of parameters to any function without causing an error. That’s
because function parameters are actually stored as an array-like structure
called arguments. Just like a regular JavaScript array, arguments can grow
to contain any number of values. The values are referenced via numeric
indices, and there is a length property to determine how many values are
present.
The arguments object is automatically available inside any function. This
means named parameters in a function exist mostly for convenience and
don’t actually limit the number of arguments that a function can accept.
NO T E The arguments object is not an instance of Array and therefore doesn’t have the
same methods as an array; Array.isArray(arguments) always returns false.
function reflect(value) {
return value;
}
console.log(reflect("Hi!")); // "Hi!"
console.log(reflect("Hi!", 25)); // "Hi!"
console.log(reflect.length); // 1
reflect = function() {
return arguments[0];
};
console.log(reflect("Hi!")); // "Hi!"
console.log(reflect("Hi!", 25)); // "Hi!"
console.log(reflect.length); // 0
Functions 21
This example first defines the reflect() function using a single named
parameter, but there is no error when a second parameter is passed into
the function. Also, the length property is 1 because there is a single named
parameter. The reflect() function is then redefined with no named param-
eters; it returns arguments[0], which is the first argument that is passed in.
This new version of the function works exactly the same as the previous
version, but its length is 0.
The first implementation of reflect() is much easier to understand
because it uses a named argument (as you would in other languages).
The version that uses the arguments object can be confusing because there
are no named arguments, and you must read the body of the function to
determine if arguments are used. That is why many developers prefer to
avoid using arguments unless necessary.
Sometimes, however, using arguments is actually more effective than
naming parameters. For instance, suppose you want to create a function
that accepts any number of parameters and returns their sum. You can’t
use named parameters because you don’t know how many you will need,
so in this case, using arguments is the best option.
function sum() {
var result = 0,
i = 0,
len = arguments.length;
return result;
}
console.log(sum(1, 2)); // 3
console.log(sum(3, 4, 5, 6)); // 18
console.log(sum(50)); // 50
console.log(sum()); // 0
The sum() function accepts any number of parameters and adds them
together by iterating over the values in arguments with a while loop. This is
exactly the same as if you had to add together an array of numbers. The
function even works when no parameters are passed in, because result is
initialized with a value of 0.
22 Chapter 2
Overloading
Most object-oriented languages support function overloading, which is the
ability of a single function to have multiple signatures. A function signature
is made up of the function name plus the number and type of parameters
the function expects. Thus, a single function can have one signature that
accepts a single string argument and another that accepts two numeric
arguments. The language determines which version of a function to call
based on the arguments that are passed in.
As mentioned previously, JavaScript functions can accept any number
of parameters, and the types of parameters a function takes aren’t speci-
fied at all. That means JavaScript functions don’t actually have signatures.
A lack of function signatures also means a lack of function overloading.
Look at what happens when you try to declare two functions with the
same name:
function sayMessage(message) {
console.log(message);
}
function sayMessage() {
console.log("Default message");
}
Looking at the code this way makes it clear why the previous code
didn’t work. A function object is being assigned to sayMessage twice in a
row, so it makes sense that the first function object would be lost.
Functions 23
The fact that functions don’t have signatures in JavaScript doesn’t
mean you can’t mimic function overloading. You can retrieve the number
of parameters that were passed in by using the arguments object, and you
can use that information to determine what to do. For example:
function sayMessage(message) {
if (arguments.length === 0) {
message = "Default message";
}
console.log(message);
}
NO T E In practice, checking the named parameter against undefined is more c ommon than
relying on arguments.length.
Object Methods
As mentioned in Chapter 1, you can add and remove p roperties from
objects at any time. When a property value is actually a function, the
property is considered a method. You can add a method to an object in
the same way that you would add a property. For example, in the follow-
ing code, the person variable is assigned an object literal with a name prop-
erty and a method called sayName.
var person = {
name: "Nicholas",
sayName: function() {
console.log(person.name);
}
};
Note that the syntax for a data property and a method is exactly
the same—an identifier followed by a colon and the value. In the case
of sayName, the value just happens to be a function. You can then call
the method directly from the object as in person.sayName("Nicholas").
24 Chapter 2
Another Random Document on
Scribd Without Any Related Topics
VITTORIA, BATTLE OF.—Fought, June 21st, 1813, between the
French and English. The following is a graphic account of this great
victory:
“The splendid achievements of the campaign of 1812 produced
their natural results. Even the torpid obstinacy of Castilian pride was
at last overcome, and by a decree of the Cortes of September 22nd,
1812, the great English General was invested with the supreme
command of the Spanish armies. He repaired to Cadiz on the 24th of
December, and on the 30th he was received by the Cortes in full
assembly. The news of Napoleon’s overthrow in Russia had just
arrived, and all hearts seemed to expand with hope of the speedy
expulsion of his troops from Spain.
England herself also now began to put forth efforts commensurate
with the crisis. At the opening of the year 1813 her land forces
consisted of 228,000 men, besides 28,000 in India, 95,000 militia at
home, and 32,000 foreign troops in the British service. And, besides
these, she had 200,000 native troops in India, a local militia of
300,000, and a yeomanry cavalry of 68,000, forming a grand total of
949,000 men in arms; and her expenditure in the year amounted to
£118,000,000 sterling.
Thus supported, her great Commander, of whom it may be
questioned if his equal in all respects ever stood upon a field of
battle, looked forward with reasonable expectation to a coming
harvest; to a campaign in which, after four years’ toils and
sufferings, the grand object of the final expulsion of the French from
Spain might be anticipated. And assuredly the means he took to gain
this end in the simplest and completest manner, were marked by the
most consummate skill and wisdom.
To be nearer to his supplies, and to relieve the wasted provinces
of Spain, Wellington had withdrawn his army into cantonments on
the Coa and the Agueda, that is, in Leon and in Beira, or Northern
Portugal. All the Lusitanian kingdom had long been free from the
French, and the campaign of 1812 had compelled them to abandon
all Andalusia Murcia, Granada, Asturias and Estramadura. The
French army now occupied only central and eastern Spain, the bulk
of the troops being quartered in New and Old Castile.
Wellington’s chief attention was naturally devoted, during the
winter, to the task of reorganizing his forces for the final struggle of
the opening year. His own English army was the only force he had
which was at all in a condition to march against the enemy. Of the
Spanish troops he found it necessary to give the Spanish Minister of
War, in March 1813, the following description:—“There is not a single
battalion or squadron in the Spanish armies in a condition to take
the field; there is not in the whole kingdom of Spain a depôt of
provisions for the support of a single battalion for one day; there is
not a shilling of money in any military chest. To move them forward
at any point now, against even inconsiderable bodies of the enemy,
would be to insure their certain destruction.”
But by unceasing exertions these evils were, in a measure,
overcome: and Wellington found himself, in the month of May, 1813,
for the first time in a state approaching to an equality with the
French. Their force, which in former years had often amounted to
nearly 400,000 men, was now reduced to 239,000 of which about
197,000 were present with the eagles. Meanwhile Wellington’s
nominal force now amounted to 200,000, and although only about
one-half of this number were fit to take the field, the remainder was
still of use in maintaining the communications, guarding convoys,
and cutting off the foraging parties of the enemy. His principal army
of English and Portuguese mustered about 75,000 men, of whom
about 44,000 were English. The efficiency of the Portuguese troops
was advanced in a surprising manner; reinforcements, especially of
cavalry, had arrived from England; and the Anglo-Portuguese troops,
conscious of an improved organization, were more confident than
ever; while the French, hearing of the calamities of their brethren in
Russia, were proportionably depressed. Even the Spaniards had, in
some numbers, been brought into better condition:—Wellington had
kept them fed and clothed during the winter, and had now several
efficient corps of native troops, ready to act in conjunction with his
own army. Hence, on the 22nd of May the great English General
began his march, and when he crossed the stream which divides
Portugal from Spain, he rose in his stirrups, and waving his hand,
exclaimed, “Good bye to Portugal!”
The military skill and talent of a commander is never more
conspicuously seen than in those manœuvres by which an enemy is
defeated without a battle. Such manœuvres often resemble the skill
and power with which an able and fearless horseman, even while on
the ground, will control a powerful courser, forcing him backwards by
a small leverage upon his mouth. In the present instance the French
still had a considerable army and able Generals, and they occupied
the centre of Spain, defending the capital, and ready to fight, if
needful, a succession of battles before they would relinquish their
prey. But their more able antagonist forced them to retreat, step by
step, without fighting, until their last and only stand was made at
Vittoria, almost in sight of France; and then delivering his attack, he
utterly routed them, and chased them over the Pyrenees. On the
22nd of May, as we have said, the English army marched out of
Portugal; on the 21st of June it fought and gained the battle of
Vittoria; and before the 1st of July the shattered remains of the
French army, with their King Joseph at their head, had fled over the
Pyrenees. Little more than a single month had sufficed to destroy,
uproot, and utterly abolish the French dominion in Spain, and that at
a time, too, when there were still 197,000 French soldiers in the
field, under many able Commanders.
A brave general of the ordinary kind would have marched in quest
of the French, lying in front of Madrid; would have defeated them,
and taken the capital. All the smaller bodies of French in Spain
would then have been called round the King; and in July a second
battle would have been fought in Arragon, or in front of Burgos. One
more victory,—a third, supposing the English to have been always
victorious, might have sent the French out of Spain; but any mistake
or mishap might have prevented this. But Wellington, by masterly
tactics, always threatening to turn the enemy’s right wing and to get
upon his communications, backed his foe as a man backs a horse, till
he could bring the opposing army into a position fit for his purpose;
and then, delivering at once a knock-down blow, he drove the whole
mass, king and army, in four-and-twenty hours, out of Spain.
King Joseph had reckoned, in the spring, upon a direct attack by
the great road of Madrid; but when it would come, or where it would
fall, he could not divine, for Wellington kept him constantly in doubt,
by a variety of feigned movements.
At last, towards the end of May, he found that Wellington, sending
40,000 men under Graham through the difficult passes of the Tras-
os-Montes, and moving himself a week after on the Esla, had carried
his whole army, by the 4th of June, over the Douro, and was now in
full march for Valladolid. If he should gain that place, Joseph well
knew that his communications would be cut off, and his whole army
taken, to use Napoleon’s phrase, “flagrante delicto.” Hastily,
therefore, Madrid was abandoned, the whole army put in retreat;
and now Joseph would make his stand at Burgos.
Thus 100 miles of Spanish ground had been cleared of the French
without firing a shot. And now, Joseph would fight for his kingdom in
this, his second position. But his Generals examined the country, and
disliked the prospect. Meanwhile Wellington pushed on, conducting
his operations continually on the same principle,—pushing forwards
his left wing, and out-flanking and turning the French right. Again
perplexed, Joseph now abandoned his second purpose, as he had
abandoned his first. Burgos must be given up, and the retreat must
be continued on Vittoria. Into Vittoria there was poured, therefore,
the artillery depôts of Madrid, of Valladolid, and of Burgos, and the
baggage and stores of several armies; with the King’s valuables, the
archives, and papers of the State and of the army, and a large
amount of treasure.
Vittoria is only 26 miles from Irun, on the French frontier. Here,
therefore, had been driven together, like a flock of sheep, the
intruders and plunderers of Spain, and one vigorous assault only was
needed to rid the land of them altogether. It was not long delayed.
It was about the 15th of June when King Joseph found his army
assembled round Vittoria, reckoning, Napier tells us, from 60,000 to
70,000 men. Wellington had left his sixth division at Medina de
Pomar, and therefore had 60,000 English and Portuguese, besides
some Spanish troops. In the number and calibre of their guns the
French had the advantage.
From the mountain-region through which the British army was
marching, the way to Vittoria lay over many a rugged steep, and
through many dangerous defiles; but no difficulty was allowed to
stop their march. “Six days they toiled unceasingly; but on the
seventh, swelled by a Spanish reinforcement, they burst like raging
streams from every defile, and went foaming into the basin of
Vittoria.”
The French army was drawn up round this basin, which is a small
plain about 10 miles in length, by 8 in breadth, through which runs
the river Zadora. As this battle-field was approached by various
mountain-passes, Wellington resolved to enter it from three sides at
once, forming three distinct combats. General Graham, with a corps
of about 20,000 men, was to attack from the British left, and to pass
the Zadora at Ariaga, near the city of Vittoria. Hill was to attack from
the right with an equal force. Wellington stationed himself in the
centre, with a rather larger force, which was to descend from the
mountain ridges, to cross the Zadora by various roads, and to march
straight upon Vittoria. In fact, the whole battle was merely an attack
on a strong army hemmed in, by an army equally strong, and
marching to the attack on three sides at the same moment.
At daybreak the English began to move; but the distance to
Vittoria was several miles, and every step was to be contended for.
Hill reached the village of Puebla about ten in the morning; pushed
on, fighting hard, till he gained the village of Subijana de Alava, and
so placed himself in communication with the English centre. Graham
had to make a march of several miles to reach Ariaga, near Vittoria;
but about one o’clock his attack began to tell. This was a serious one
for the French; for, if successful, it would cut them off from the great
road to Bayonne. King Joseph, finding both his flanks thus
threatened, sent an order to the centre to retire. But the troops were
fiercely engaged, and retreat was difficult. Meanwhile, however,
three attacks of the English, right, left, and centre, were all
succeeding; and step by step, the French were being pushed back
upon Vittoria.
“At six o’clock,” says Napier, “the French reached the last
defensible height in front of Vittoria. Behind them was the plain in
which the city stood, and beyond the city were thousands of
carriages and animals, and of men, women, and children, crowded
together in all the madness of terror; and as the English shot went
booming overhead, the vast crowd started and swerved with a
convulsive movement, while a dull and horrid cry of distress arose;
but there was no hope, no stay for army or multitude, it was the
wreck of a nation!” Still the courage of the French soldiers was
unquelled. Their artillery for a time kept the Allies in check, but
suddenly the fourth English division, rushing forward, carried a hill
on the left, and the heights were at once abandoned. Joseph finding
the main road so completely blocked up by carriages that the
artillery could not pass, indicated the road of Salvatierra as the line
of retreat, and the army went off in a confused and yet compact
body on that side, leaving Vittoria on its left. The British infantry
followed hard, and the light cavalry galloped through the town to
intercept the new line of retreat. All became disorder and confusion,
the guns were left, while the artillerymen fled with the horses.
Vehemently and closely did the British pursue, and nothing could
stop their victorious career until night and the disappearance of the
flying masses had ended the struggle. The French lost all their
artillery, all their baggage, all their equipages, all their stores,
treasures, and papers, “so that no man,” says a French writer, “could
prove even how much pay was due to him. Generals and
subordinate officers were alike reduced to the clothes on their backs,
and many of them were barefooted.”
“Never was victory more complete. The trophies were
innumerable. Marshal Jourdan’s baton of command was brought to
Lord Wellington, who sent it to the Prince Regent, from whom he
quickly received one of an English marshal in return. The loss of the
French was never ascertained; that of the Allies was 3,567 English,
1,059 Portuguese, and 550 Spanish. The spoil taken was enormous.
“The soldiers of the army,” wrote Lord Wellington, “have got among
them about 1,000,000 sterling in money, with the exception of about
100,000 dollars found in the military chest. Rich vestures of all sorts,
gold and silver plate, pictures, jewels, parrots, monkeys, and
children, lay scattered about the field amidst weeping mothers and
wailing children. Joseph himself narrowly escaped; a squadron of
dragoons pursued his carriage and fired into it.”
All the remaining bodies of the French in Spain fell in the fall of
Vittoria. They escaped out of the kingdom by various roads as
quickly as possible. “Joseph’s reign was over, the crown had fallen
from his head, and after years of toil and combats, which had rather
been admired than understood, the great English leader, emerging
from the chaos of the Peninsular struggle, stood on the summit of
the Pyrenees a recognized conqueror. From those lofty pinnacles the
clangour of his trumpets pealed clear and loud, and the splendour of
his genius appeared as a flaming beacon to warring nations.”[15]
Thus, in some five or six weeks, had a great kingdom been
cleared of its invaders and oppressors—not by the power of superior
numbers, but by the natural ascendency of a consummate military
genius. “Here,” remarks Napier, “was a noble army driven like sheep
before prowling wolves, although in every action the officers had
been prompt and skilful, and the soldiers brave, firm, and obedient.
The French troops were excellent and numerous, and the country
strong and favourable for defence; but the soul of a great
Commander was wanting; and hence, the Esla, the Tormes, the
Douro, the Pisuerga, seemed to be all dried up, the mountains to be
levelled; and 60,000 veteran soldiers, willing to fight at every step,
were hurried with all the tumult and confusion of defeat across the
Ebro.”
The deliverance of the Peninsula, by a force so far inferior to that
of the French, must always remain one of Wellington’s greatest
glories. The same French writer, whom we have already quoted,
Jules Maurel, remarks this surprising fact. He says: “The truth is,
that from 1808 to 1813, Wellington never had 30,000 English under
his orders, even at a period when the Imperial armies deluged the
Peninsula with no fewer than 370,000 men.”
Nor were the results of this great day confined to the Spanish
peninsula. Like its predecessor, the victory of Salamanca, the battle
of Vittoria shook the whole continent of Europe. Napoleon himself,
holding his ground at Dresden, had, up to this moment, succeeded
in withholding Austria from any actual participation in the
confederacy against him. He had even succeeded, on the 30th of
June, in obtaining a convention for the restoration of peace between
himself, Russia and Prussia. But the very next day the news of the
expulsion of the French from Spain reached Dresden, filling
Napoleon and his ministers with consternation, and giving new life
and vigour to the Russian and Prussian councils. The Allies regretted
that any cessation of arms had been agreed to, and they began to
long for its termination. The very moment it expired by lapse of
time, Austria joined the Allies; war was actively resumed, and the
autumn had not ended before Napoleon had been driven across the
Rhine, and Germany freed from the presence of the French armies.
The French writer from whom we have just quoted, Jules Maurel,
thus notices this remarkable passage in modern history:
“Scarcely had the armistice been signed when intelligence arrived
that the French had lost everything in Spain. In 40 days Wellington
had turned, one after another, all the positions occupied by the
French armies of the centre, of the south and of the north, and had
crossed the Tormes, the Douro, the Esla, the Carrion, and the Ebro.
He had reached Vittoria; he had gained a decisive battle; he had
expelled King Joseph from the Peninsula, and had planted his army
on the Pyrenees. In the beginning of May he was in Portugal; on the
23rd of June he was on the frontiers of France. The defeat of Vittoria
entirely neutralized the victories of Lutzen and Bautzen, and at once
restored the coalition.”
VOUGLE, BATTLE OF.—Fought between Alaric II and Clovis of
France. Alaric was entirely overthrown, and the whole country
subdued. Clovis afterwards made Paris the capital, and became the
founder of the French Monarchy.
W.
“We have seen the three several stages by which the Duke of
Wellington had conducted the British army to that elevated position
in which the peace of 1814 left it. We have seen how it had, first, on
the broad fields of Castile, boldly encountered a French army of
twice its strength, and had sent it back in defeat. Next, at
Salamanca, meeting an army of equal force, it had scattered it by an
assault of a single hour, annihilating at a blow one-half of its
strength. And lastly, falling upon the intrusive King himself in his final
position of retreat and defence at Vittoria, it had driven his entire
array, like a flock of frightened sheep, over the Pyrenees. After those
triumphs, by which a whole realm of great extent had been delivered
from its invaders, there seemed scarcely any way by which the fame
and honour of the British army and its illustrious Commander could
be enhanced, except by an event not to be anticipated—an
encounter with the great conqueror of modern times, now an exile
at Elba; and a triumph over him.
This event, however unlikely it might seem, was reserved for
England’s soldiers and her General; and it occurred in less than a
year after the apparent restoration of peace. Napoleon suddenly left
his island-home, reappeared in France, gathered his soldiers round
him, and re-entered Paris as once more its Emperor. Naturally
enough, the Sovereigns who had compelled his retirement, scarcely
nine months before, resolved to maintain their position; and they
covenanted with each other to place armies amounting to 600,000
men on the soil of France in the course of July, 1815. The British
portion of this force was collecting together in the months of May
and June, under the Duke’s command; when Napoleon determined
not to wait for the attack, but to carry the war into the allied
territories; and, accordingly, in the second week in June he entered
Belgium. Before he had proceeded twenty miles he encountered
both the English and the Prussian armies, and on the fourth day, at
a distance of about thirty miles from the French frontier, was fought
the great and decisive battle of Waterloo.
This momentous contest will require of us a more lengthened
description than we have given of any of the great battles; both
because it was an event of the highest possible importance to the
fate of England, of Europe, and of the world; and also because it
was, so to speak, a succession of battles fought on one field, and on
the same day. In a former case we have seen “an army of forty
thousand men defeated in forty minutes;” but here the deadly strife
occupied nearly ten hours. The French opened the attack at eleven
in the morning, and at nine o’clock at night the last of their
battalions had not yet quitted the field. In the course of these ten
hours four or five desperate and prolonged contests had taken
place; each of which might have been justly called a battle. It will be
impossible, therefore, to give any fair or complete idea of this long
continued struggle, without occupying much greater space than is
required for an ordinary battle.
It is also a history which is thickly strewn with controversies. The
defeated General himself was the first to open this wordy strife. The
loss of the fight of Waterloo was a fact to which he never could be
reconciled. That battle hurled him, finally, from the throne on which
he had for the second time seated himself, and sent him to wear out
the few remaining years of his life on the rock of St. Helena. In that
retirement he occupied himself, for the most part, in a series of
efforts to resuscitate his extinguished “glory.”[16] In these attempts
he was hampered by no moral scruples; for, as Emerson has
remarked, “this, the highest-placed individual in the world, had not
the merit of common truth and honesty; he would steal, slander,
assassinate, as his interest indicated.” Any reasonable man,
therefore, will read his “Historical Memoir,” book ix, written at St.
Helena, and published in London in 1820, with that caution which is
so plainly called for when a document is confessedly an exparte
statement, and written by one who is known to be of unscrupulous
character.
Yet that document has been received in many quarters with a
credulity which is somewhat surprising. It is true that this credulity
may be accounted for in the case of the French historians—who,
obliged to confess that their defeat at Waterloo was “horrible”—a
“massacre”—a “deluge of blood”—are glad to have supplied to them,
under Napoleon’s own hand, the apology that he was overmatched
and greatly outnumbered; and that yet, after all, he would have
proved victorious if one of his Generals had not disobeyed his
commands.
The latter of these two pleas has been generally rejected by
English writers—utterly denied as its truth has been by the party so
accused. But, strangely enough, although there was every
probability that Napoleon’s account of his own strength, and of that
of his opponent, would be wholly untrustworthy—several of our best
English writers have given entire credence of his statement of the
real amount of his army; even while those statements are clearly
refuted by abundant testimonies of many Frenchmen. And this point
is not an immaterial one. For if we could admit the truth of
Napoleon’s final conclusion, that “On that day 69,000 French beat
120,000 men, and the victory was only torn from them between
eight and nine o’clock at night by the increase of the allies to
150,000 men”[17]—what merit could we assign to the British soldiers,
or to their great commander, for such a victory? But, in sober verity,
of all the falsehoods deliberately put forth by Napoleon in the course
of his life, this, probably, is nearly the greatest.
Let us, however, now endeavour to arrange our narrative in its
proper order. The army which was assembling in Belgium under the
Duke’s command, had reached, in the beginning of June, the
respectable amount of almost 100,000 men. It contained, however,
far more Belgians, Hanoverians, Brunswickers, and Dutchmen, than
British troops, and far more new levies, landwehr, and militia, than
of experienced soldiers. The English regiments which had followed
the Duke through all the fields of Spain had been sent to America,
and were now on the Atlantic, on their return home. He had some of
the Guards, and a few other regiments of some standing; but the
largest portion of the British troops which had yet reached Belgium
were second battalions—new recruits drafted from the militia—and
the same observation would apply to the Hanoverians and other
auxiliaries.
It was a knowledge of this intrinsic weakness of the Duke’s army,
and of the fact that 10,000 or 15,000 of his old Peninsular troops
would soon join him, that decided Napoleon, as is frankly confessed,
[18]
to make a sudden attack on the British and Prussian forces
before they were fully prepared to meet him. Silently, therefore, but
with his usual skill and rapidity, Napoleon brought together a
powerful army, and on the morning of the 15th of June he moved
forward and entered Belgium.
And here we are met by the most current of all the fictions which
are connected with this history. A variety of writers have repeated,
one after another—Napoleon himself setting them the example—the
story that the Duke never heard of the approach of the French until
eleven o’clock in the evening of that day, while at a ball at Brussels.
The facts, however, which are beyond dispute, are these—that the
French did not enter Charleroi, the first Belgian town, until eleven or
twelve o’clock on June the 15th—that tidings of their movement
reached the Duke at Brussels by three o’clock, and that between
four and five o’clock that same afternoon orders went out to every
corps of the British army to move to the front, many of them
beginning their march that same evening. There was no surprise,
then, nor was there the loss of a single day. The French had not
marched thirty miles—had not entered any place of the least
importance, when, on the third day, they found the British army
drawn up across their path, and had to fight the battle of Waterloo.
They had, indeed, found their progress arrested still earlier.
Entering Belgium on the 15th, they were stopped the very next day
at Ligny by the Prussians, at Quatre Bras by a part of the English
army. Marshal Blucher being defeated, and retiring a few miles, the
Duke fell back also, and thus was enabled to draw up his army at
Waterloo—a position which he had before observed to be an
advantageous one, and which was in all respects well suited to the
defence of Brussels.
It was on the afternoon of the 17th June that the Duke’s army
found itself assembled on this spot. The French army, led by
Napoleon himself, soon approached, but the day was too far
advanced to afford time for a general engagement. The two armies,
therefore, took position, the English on a rising ground called Mont
St. Jean, about half a mile in advance of the village of Waterloo, and
nine miles on the French side of Brussels; the French on a series of
heights facing Mont St. Jean, having the village of Planchenoit on
the right, and looking down upon a small valley which separated the
two hosts.
And now we are naturally brought to a consideration of the
question, what was the respective strength of these two armies?
This is a point upon which Napoleon has bestowed great pains in his
“Historical Memoir, Book ix,” and on which he has succeeded in
deluding many English writers.
As to the strength of the British army, there can be no kind of
doubt upon that point, for the actual numbers present in each
battalion and squadron was carefully recorded; and these records
were needed to establish the respective rights of all present to
honours and rewards. We have spoken of a gross amount of nearly
100,000 men. But of these, several thousands were required to
garrison Antwerp, Ostend, Nieuport, Ypres, Tournai, and Mons,—the
loss at Quatre Bras had been 3000 or 4000, and a post of
observation at Hal, consisted of nearly 6000. When these deductions
were made, not quite 70,000 men remained, to meet Napoleon’s
attack at Waterloo.
The British infantry in the field were 15,181, and the German
Legion infantry were 3301. The British and German cavalry were
7840, and their artillery was 3493. Thus the whole reliable force of
the Duke—the force to which he must look to stand the French
attack—was not quite 30,000 men. All this was well known to
Napoleon, who, in his “Book ix,” says, “Victory appeared to be
certain,” for the French army consisted of “good troops, while, in the
enemy’s army, the English only, amounting to 40,000 at most, could
be reckoned upon as such.”[19]
The “Allied troops,” who made up the Duke’s array, consisted of
10,755 Hanoverians, many of whom were mere landwehr or militia,
and nearly 25,000 Belgians, Dutch, and men of Brunswick and
Nassau. Some of these fought gallantly, but others retreated
whenever the French approached,—some actually flying from the
field. Hence Napoleon justly says, “one Englishman might be
counted for one Frenchman:—two Dutchmen, Prussians, or soldiers
of the Confederation, for one Frenchman.”
Adopting, therefore, Napoleon’s own method of calculation, we
may say, that the Duke had an army nominally amounting to about
68,000 men, really equal to something less than 50,000.
And now we turn to the other side of the account. Here we must,
to be safe, accept only French testimony. If we draw together all the
credible statements of this class that we can find, we shall probably
be able to arrive at a just conclusion.
There was published at Paris, in 1815, a volume by an officer
attached to the staff, which may be considered to be “the French
account,” at the time and in detail, of this battle. In this volume, the
whole army which entered Belgium is stated to have been “150,000
effective men of whom about 30,000 were cavalry.” It seems
improbable that a staff-officer should have greatly erred, or that a
Frenchman should have exaggerated the strength of the beaten
army. Reckoning, therefore, the gross number to have been
150,000; and deducting 15,000 for losses at Ligny, and at Quatre
Bras, we may estimate the force detached under Grouchy on the
17th, at about 38 or 40,000 men, and the strength of the French
army at Waterloo at something more than 90,000.
And this estimate precisely agrees with Napoleon’s own statement,
written at Paris three days after the battle. In this bulletin he says,
“We estimated the force of the English army at 80,000 men. We
supposed that a Prussian corps which might be in line toward the
right might be 15,000 men. The enemy’s force, then, was upwards
of 90,000 men; ours less numerous.”
He is here speaking of the morning. But there was not a Prussian
soldier in the field until five o’clock in the afternoon; and this
Napoleon well knew. Why, then, does he here introduce a
“supposed” Prussian corps? Clearly, in order to bring up the allied
force to 95,000 men, so that he might be able to add, “Ours, less
numerous.” He had every possible motive, as a beaten General,
striving to make the best of his case,—for saying, if he had dared,
—“The enemy was more than 90,000 strong, but we had not quite
70,000.” But he could not venture, in the face of abundant evidence
then existing, to say that his army was less than 80,000, the force
he assigns to the English. He therefore, by an “ingenious device,”
augments the allied force to 95,000; and then he can venture to
assert that his own army was inferior in numbers. There is clearly
implied in this statement an admission that his own force was not
greatly below 95,000.
Yet when Ney and others were dead, and the records, in all
probability, scattered or destroyed, the same man who wrote this
bulletin, concocted at St. Helena, four or five years after, a widely-
different account. In his “Book ix,” p. 128, he puts forth an elaborate
table, purporting to show, that the whole force of the French army
at Waterloo was only 68,650 men! And such has been the imposing
effect of this table, that many English writers, while they could
detect the falsehood of other statements in that same volume, still
accepted, as an undeniable fact, the conclusion, that Napoleon’s
army at Waterloo consisted of only 68,650 men! Yet only common
prudence, and the use of a little careful scrutiny, was needed, to
prove that these same elaborate tables in “Book ix” were nothing
more than what is usually called, in railway language, “a cooked
account.”
The proof of this shall be given from French writers alone. And,
first, let “Book ix” refute itself, by its own self contradictions. At page
71, it gives the second corps, 19,800 infantry; while at p. 95-97, it
states the same infantry, at the same moment, at 21,000. At page
128 it gives the first corps 16,500 infantry, and at table F it calls the
same infantry, 17,600. At page 128 the cavalry of the Guard and the
third and fourth corps of cavalry are stated at 10,000; while at pp.
158 and 173 they are twice called 12,000. At p. 35 we are told that
“the regiments generally had but two battalions; each battalion
consisting of 600 men, present and under arms.” Yet in the principal
table, F, the regiments are always estimated at either 1000 or 1100
men, the battalions at 500 or 550. Thus it is abundantly clear, even
from the pages of “Book ix” itself, that its writer is one who “plays at
fast and loose with figures.”
But other refutations, from purely French sources, are abundant.
We have seen that Napoleon states, in “Book ix,” p. 35, that his
battalions had 600 men; but that he quietly puts them down in table
F, as being only 500 or 550.
Now in his portfolio, captured at Charleroi, and published at
Brussels, there was one report, made by an officer named De
Launoy, and dated “Montalimert, June 4th,” which said, “The first
battalion, 720 strong, marched on the 1st of June.” And, in the
Moniteur of May 28th, published at Paris under Napoleon’s own
authority, there was given a letter dated “Lille, May 26th,” which
says, “Our garrison is entirely composed of battalions of select
troops, which successively arrive: the 20th arrived yesterday; almost
all consist of 720 men; we are expecting two battalions of veterans.”
Now these troops formed part of the first corps, as stated in “Book
ix,” p. 31; and in table F they are all set down as having in each
battalion, 550 men!
It was of this first corps that Marshal Ney spoke in his letter of
June 26th, 1815, in which he complained of having it taken away
from him on the 16th. He describes it as having consisted of
“between 25,000 and 30,000 men.” He must have had the actual
returns in his pocket when he wrote this. Now if the battalions
generally consisted of 720 men, as the Moniteur of May 28th had
told us, then its thirty-two battalions would have contained 23,040;
which added to 1400 cavalry, and 1564 artillery men, would be
accurately described as “between 25,000 and 30,000 men.” But
Napoleon, in his statement of the force at Waterloo, sets down the
infantry of this corps as only 16,500; thus contradicting at once the
statement of the Moniteur, the report found in his own portfolio, and
the declaration of the Marshal who commanded that corps!
In the same spirit, in the table of the troops at Waterloo, (Book ix,
p. 128,) we find the infantry of the Guard set down as being 11,500.
Yet Gourgaud, Napoleon’s Aide-de-Camp, and Fleury de Chaboulon,
his secretary, both concur in stating this infantry to have been
14,000.[20]
Of the heavy cavalry we have already seen, that while Napoleon,
in his table, at p. 128, sets it down at 4000, 3000, and 3000, or
10,000 in all, he afterwards twice describes it, at p. 158 and at p.
173, as “these 12,000 select horse.”
Once more, in “Book ix,” p. 129, he states the force detached
under Grouchy to have been 34,300. His own companion at St.
Helena, General Montholon, in his history, (vol. i, p. 14,) calls this
force 42,000.
All this evidence, then, drawn from several quarters, but wholly
French, points to one conclusion,—namely, that Napoleon, in forming
his tables for “Book ix,” deliberately reduced his real strength at
Waterloo by about one-fourth or one-fifth; and that his first
statement, in his bulletin issued at the time, was the true one;
namely, that his army was only somewhat “less numerous than
95,000.”
And to this conclusion a remarkable support is found, in the
behaviour of the two Generals on the day preceding the action.
Wellington had beaten nearly every one of Napoleon’s Marshals;[21]
—and could not but feel a degree of exultation at the thought of
meeting the master of them all. Napoleon, on his part, had to
encounter a General who had never been conquered. Supposing,
then, the armies to have been nearly equal in strength, what might
have been anticipated, but a degree of eager anticipation on
Wellington’s side, and of seriousness on Napoleon’s? Instead of
which, what do we hear? The Duke writes to Marshal Blucher, that
he will accept battle, if the Marshal will assist him with one corps of
his army. Meanwhile, Napoleon’s only anxiety is lest the English
should escape him. “He was surprised,” writes his secretary, Fleury,
“when daylight discovered to him that the English army had not
quitted its positions, but appeared disposed to accept battle.” “He
returned to his head-quarters (Book ix, p. 125) full of satisfaction at
the great fault committed by the enemy’s General.” “He held this,”
says Brialmont, “to be rashness, and a fault, exclaiming, ‘At last,
then, I have them,—these English!’” Do not these views and
anticipations, on the part of both of the Generals, make it quite
evident that each of them was fully aware of the great superiority of
the French army; and of the temerity of which the Duke would be
guilty if, without any assurance of support, he ventured on an
engagement in the face of such odds?
It is worth remark, too, that while several of the best English
writers have accepted with the most good-natured simplicity,
Napoleon’s own account of the force with which he fought this battle
—French historians, even when admirers of Napoleon, show much
less faith in his assertions. Thus, Lamartine, having Napoleon’s ixth
Book before him, in which the number, “sixty-eight thousand, six
hundred and fifty men,” is strenuously insisted on—quietly
disregards the fiction, and repeatedly speaks of the French force as
being “eighty thousand men.”[22]
But Napoleon’s “certainty of success,” of which he speaks at p.
127 of his Book ix, rested more upon the superior quality of his
troops than on their superior numbers. He was thoroughly well
aware, both of the slight value of the Belgian and Hanoverian
auxiliaries, and of the excellence of his own troops. And the Duke,
also, knew full well both of these facts. On the 8th of May he had
written to Lord Stewart, “I have got an infamous army; very weak
and ill-equipped; and a very inexperienced staff.” And seven days
after the battle, he repeated to Lord Bathurst, that he had got “not
only the worst troops, but the worst-equipped army, with the worst
staff, that ever was brought together.”[23]
On the other hand, Napoleon’s army was, for its amount, the
finest that he had ever led into the field. Thus his secretary, Fleury,
says, “The whole army was superb, and full of ardour.” Lamartine
speaks of it as “his grand army of chosen men; every battalion of
which had a soul equal to the utmost extremity.” Napoleon himself,
in “Book ix,” says: “The spectacle was really magnificent: the earth
seemed proud of being trod by such intrepid combatants.” And at St.
Helena he told O’Meara: “My troops were so good, that I esteemed
them sufficient to beat a hundred and twenty thousand.”[24]
Thus, as Brialmont remarks, whatever might be the numerical
proportion of the two armies, “when we come to look at the
respective qualities of the troops, the inferiority of the Anglo-Belgian
army was enormous. Not only was it composed of heterogeneous
elements, but it consisted almost entirely of young soldiers, a large
proportion of whom had never been under fire. The Hanoverian
contingent was made up of militia; and many regiments were fit only
for garrison duty.”[25]
The evening which preceded the memorable 18th of June was
dark and cloudy; the rain fell in torrents, and the men were often
ankle-deep in water. But, however deplorable might be their outward
condition, the interest of this eventful moment rendered the
combatants on either side, almost insensible to physical sufferings.
Every man in both armies knew that a great and decisive battle was
to be fought on the following day. With the opening morning, then,
would begin what might prove the final contest,—ending a strife of
nations which had lasted more than twenty years. The two greatest
Generals of the age were for the first time to be brought into
collision: the conqueror of Europe was to measure swords with the
deliverer of Spain. No two such leaders, it has been well observed,
had confronted each other, since Hannibal and Scipio met at Zama.
Doubtless, and very naturally, the greatest degree of confidence
was felt in the camp of the invaders. The French soldiers relied with
reason on the extraordinary talents of their great leader, victorious in
fifty contests, foiled in scarcely any. The men who stood by his side,
too, were the veterans who had marched triumphantly over many
victorious fields, and who now felt defeat, under such a Captain, to
be scarcely possible. They were confident, too, in their numbers. All
of them had heard that the Emperor had carried over the frontier a
picked army of 150,000 men. They saw on the heights around them
the first and second corps, amounting together to nearly 50,000
men, with the sixth, less numerous, in reserve. The Imperial Guard
was there, from 18,000 to 20,000 strong,—the finest troops that
France had ever possessed, and the cuirassiers, nearly 6,000 in
number. What could a mixed force of a few English, joined with
Belgians, Hanoverians, and Dutchmen, do against such a power?
Very naturally, therefore, we learn from Gourgaud, that “the
French troops were full of enthusiasm. Such were the acclamations
of joy, that they prevented the orders from being heard.”[26] From
Napoleon to his Generals, from the Generals to the troops, the
feeling had spread and become universal. “Ah! we have them, then,
—these English!”
The British troops had not the same ground of confidence. They
knew well that their own numbers did not amount to one-third of
the strength of Napoleon’s army, and that the Hanoverian and
Belgian landwehr, by whom their line was to be filled up, were of
very uncertain value. Many of the battalions, both English and
foreign, had never been in action before. Still, they had a great and
well-founded trust in their Commander; and with a spirit like his
own, they meant to do their duty, and while they lived, to stand
their ground.
The field of Waterloo, or the heights of Mont St. Jean, as the
English and the French respectively call this spot, is a piece of
slightly-elevated ground lying, as we have already said, about 1000
yards in advance of the village of Waterloo. Brussels, in which
Napoleon intended to sleep that night, was about nine miles in the
rear of the English army. The main road from Charleroi to Brussels
passed through the French position, descended into the valley, and
then ascended Mont St. Jean, cutting the English position at right
angles near a farm-house called La Haye Sainte. The English line lay
about 200 yards behind this farm-house. Here was the centre and
left centre. In advance of the right wing of the English army, and
between it and the left wing of the French, stood a larger house,
surrounded by walled gardens and orchards, and called
Hougoumont. As this place would have afforded great advantages to
the French in preparing attacking columns, the Duke placed in it
some companies of the Foot-Guards, with some Nassau and
Hanoverian troops, and enjoined its resolute defence. Well were his
orders obeyed, for the utmost efforts of a whole army corps of the
French were ineffectual to carry this position. The French lost 6 or
8000 men in the attempt, but up to the very close of the day the
English Foot-Guards maintained their possession.
The position of Waterloo was deliberately chosen by the Duke,
and the choice is commended by all unprejudiced critics. Yet
Napoleon, ungenerous throughout, strives to depreciate his
antagonist’s judgment in this particular. He says, in “Book ix:”—“The
English General had in his rear the defiles of the forest of Soignes,
so that if beaten, retreat was impossible” (p. 125). Upon which M.
Lamartine observes: “In fighting on the borders of a forest fortified
in all its approaches, as well as by its own impenetrability, the Duke
had every pledge of victory, if victory was possible; and of a secure
retreat if defeat were unavoidable. Waterloo was an admirable field
of battle, and it is to be regretted that Napoleon has not
acknowledged this, but has obstinately striven to prove that his
conqueror was unworthy of him. These are the littlenesses of glory.
The choice of Waterloo on Wellington’s part was a further mark of
that genius, at once resolute, powerful, and prudent, which has
characterized all the campaigns of this General.”
It should be added, that the Duke, during five years of constant
warfare with the French armies, had never once been beaten by
them in a pitched battle. Nor had he any thought of retreating upon
the present occasion, or any desire to make a special provision for
such an emergency. In after years he dropped the remark: “I knew
that they could never so beat us, but that we could have made good
the forest against them.”
And now the several divisions of the two armies were placed in
the positions which to the two commanders seemed suitable. On the
left of Napoleon’s line he placed his second corps, which he himself
states to have consisted of 17,000 men, and which undoubtedly was
nearer 20,000. This corps, to which his brother Jerome was
attached, was ordered to seize upon Hougoumont, and then to
attack the right of the British army. Napoleon’s right wing was
formed of his first corps, under Ney’s command. This corps had not
yet been in action, and was complete. Napoleon sets down its
strength us 17,900 men; but Ney, who commanded it, describes it as
“from twenty-five to thirty thousand.” In the second line stood the
sixth corps, consisting of 7 or 8000 men; the heavy cavalry, of about
7000; and in a third line stood the Imperial Guard, which, of cavalry
and infantry, had at least 18,000. The artillery numbered more than
6000 men, with 240 cannon. The entire force was probably
described with truth in Napoleon’s bulletin of the battle, in which he
calls it “less than 95,000.”
Against these the Duke had to place in position, on the opposite
heights, his 15,181 British infantry, his 3,300 infantry of the German
Legion, and about 28,000 Belgians, Hanoverians, and Brunswickers.
Many of these showed themselves, in the battle, unable to stand a
French attack. In the second line he had 7,840 English and German
cavalry, and about 4,500 Belgians, Hanoverians, and Brunswickers.
His artillery (English, Belgian, &c.,) were 5,600 and his guns, 156. At
Hal and Enghien, on the road from Mons to Brussels, the Duke
placed a detachment of 5,819 men to guard against any possible
device in that quarter. These could take no part in the battle, being
fixed by their orders at a distance of several miles from it.
The Duke had slept for a few hours at his headquarters in the
village of Waterloo, and then rising before dawn on the morning of
the 18th he wrote several letters, in which he expressed his
confidence that all would go well, but still gave specific orders for all
that was to be done in Brussels, Antwerp, &c., in the event of the
success of the French attack. He then saw to the distribution of the
reserves of artillery, which had been packed in the village, so that
supplies should be readily forwarded to every point where they
might be needed. He also personally inspected the arrangements
made for the reception of the wounded. Then mounting his horse
Copenhagen, he rode to Hougoumont, and thence down a lane
leading through the wood beyond it. Halting on the eastern slant of
the thicket, he narrowly surveyed all of the enemy’s arrangements
that could be seen. Then giving some final orders at Hougoumont,
he galloped back to the high ground in the right centre of his
position, where he began to chat with the members of his staff with
as much liveliness as if they were about to take part in an ordinary
review.
There was now a pause of considerable duration. This was one of
the chief mistakes committed by Napoleon. He had before him, as
he well know, an army exceedingly inferior to his own; so inferior, in
short, that it was a matter of joyful surprise to him that the Duke
had not decamped in the night. But on his right he knew that there
was Grouchy with less than 40,000 men, opposed to Blucher, who
had 80,000 or 90,000. It was obvious to every one that the Prussian
general might, and probably would, engage Grouchy with one or two
corps, and carry the rest of his army to the succour of the English. It
was, then, a great error not to use the present opportunity with
decision and rapidity. He accounts for the delay by the state of the
ground; but when Grouchy justified his inertness at Wavre by the
same plea, Napoleon exclaims, in “Book ix,” p. 153, “The dreadful
state of the weather, ridiculous motive!”
The village clock was striking eleven when the first gun was fired
from the French centre, and this great battle began, which only
ended with the darkness of night. There has never been a battle
which was so distinctly divided, like a drama, into four or five acts.
These were: 1. The attack on Hougoumont and the English right; 2.
The attack on La Haye Sainte and the English centre and left; 3. The
irruption of the French heavy cavalry upon the centre of the English
position; 4. The Prussian diversion; 5. The charge of the Imperial
Guard, and final defeat of the French army. These several acts or
stages in this great contest usually followed each other at intervals
of about two hours, i.e. at 11, at 1, at 3, at 5, and at 7 o’clock.
There cannot, therefore, be a better way of obtaining a clear idea of
the progress of this tremendous struggle, than by passing in review
these five acts or stages, just us they occurred, and distinctly from
each other.
ELEVEN O’CLOCK.
Precisely at this hour the French artillery opened fire upon the
orchards of Hougoumont, and Jerome, with his division, moved
forward to the attack. As we have seen, Napoleon himself assigns to
his second corps, to whom this duty was assigned, a strength of
17,900 men; and, reasoning upon his uniform practice of diminishing
his real numbers, we may safely estimate its real force at 20,000.
This corps was to storm and take Hougoumont, and then, from this
position, to annoy and perhaps to attack with success, the Duke’s
right. But it never succeeded even in its first object. The whole
power of these 18,000 or 20,000 men failed to carry a post which
was never garrisoned by so many us 2,800. Thus, Gourgaud tells us
that at noon “Prince Jerome with his division took possession of the
wood: he was driven out, but a new attack once more rendered him
master of it. The enemy, however, kept possession of the largo
house in the centre.” Again, at half-past four, he says, “General Reille
supported the attack of Jerome’s division by Foy’s division. (Each
being 5,000 or 6,000 strong.) Howitzers had set fire to the house
and nearly destroyed it; three-fourths of the wood was in our
possession; the fields were strewed with the English guards, the
flower of the enemy’s army.” But beyond this partial success the
French never attained. They never carried the chateau itself, but in
the attempt they lost from 6,000 to 8,000 men, while the killed and
wounded of the defenders amounted to a few hundreds only. This
portion of the battle lasted from noon until night, and all that the
French could boast of, was, that with five or seven times the number
of the British, they obtained possession of “three-fourths of the
wood.”[27] Napoleon says, in “Book ix,” “The wood remained in the
possession of the French; but the chateau, in which some hundreds
of intrepid English troops defended themselves, opposed an
invincible resistance.”[28]
ONE O’CLOCK.
THREE O’CLOCK.
ebookgate.com