100% found this document useful (2 votes)
120 views

The principles of object oriented JavaScript Zakas instant download

The document discusses 'The Principles of Object-Oriented JavaScript' by Nicholas C. Zakas, which explores JavaScript's object-oriented nature and unique inheritance patterns. It aims to help developers write clearer and more efficient code by understanding JavaScript's handling of objects and functions. The book is designed for those familiar with traditional object-oriented languages and seeks to deepen their understanding of JavaScript's capabilities.

Uploaded by

ciubaglovepc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
120 views

The principles of object oriented JavaScript Zakas instant download

The document discusses 'The Principles of Object-Oriented JavaScript' by Nicholas C. Zakas, which explores JavaScript's object-oriented nature and unique inheritance patterns. It aims to help developers write clearer and more efficient code by understanding JavaScript's handling of objects and functions. The book is designed for those familiar with traditional object-oriented languages and seeks to deepen their understanding of JavaScript's capabilities.

Uploaded by

ciubaglovepc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

The principles of object oriented JavaScript

Zakas download

https://ebookgate.com/product/the-principles-of-object-oriented-
javascript-zakas/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Object Oriented JavaScript Create scalable reusable


high quality JavaScript applications and libraries 1st
Edition Stoyan Stefanov

https://ebookgate.com/product/object-oriented-javascript-create-
scalable-reusable-high-quality-javascript-applications-and-
libraries-1st-edition-stoyan-stefanov/

Object Oriented Oracle Wenny Rahayu

https://ebookgate.com/product/object-oriented-oracle-wenny-
rahayu/

Management of the Object Oriented Development Process


1st Edition Liping Liu

https://ebookgate.com/product/management-of-the-object-oriented-
development-process-1st-edition-liping-liu/

Principles of object oriented modeling and simulation


with Modelica 3 3 a cyber physical approach 2nd Edition
Fritzson

https://ebookgate.com/product/principles-of-object-oriented-
modeling-and-simulation-with-modelica-3-3-a-cyber-physical-
approach-2nd-edition-fritzson/
PHP Object Oriented Solutions 1st Edition David Powers

https://ebookgate.com/product/php-object-oriented-solutions-1st-
edition-david-powers/

Object Oriented Programming with C 2 e Second Edition


Sahay

https://ebookgate.com/product/object-oriented-programming-
with-c-2-e-second-edition-sahay/

Object Oriented Design and Patterns 2nd Edition Cay S.


Horstmann

https://ebookgate.com/product/object-oriented-design-and-
patterns-2nd-edition-cay-s-horstmann/

Object oriented programming with ABAP Objects 1st


Edition James Wood

https://ebookgate.com/product/object-oriented-programming-with-
abap-objects-1st-edition-james-wood/

Object oriented programming in C 7th print. with


corrections Edition Lafore

https://ebookgate.com/product/object-oriented-programming-
in-c-7th-print-with-corrections-edition-lafore/
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

THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT


OBJECTS at TandemSeven

If you’ve used a more traditional object-oriented


language, such as C++ or Java, JavaScript probably
• How to define your own constructors

• How to work with and understand prototypes


J A V A S CR I PT
doesn’t seem object-oriented at all. It has no concept
of classes, and you don’t even need to define any • Inheritance patterns for types and objects
objects in order to write code. But don’t be fooled —
JavaScript is an incredibly powerful and expressive
The Principles of Object-Oriented JavaScript will leave NICHOLAS C. ZAKAS
even experienced developers with a deeper understand-
object-oriented language that puts many design
ing of JavaScript. Unlock the secrets behind how objects
decisions right into your hands.
work in JavaScript so you can write clearer, more
In The Principles of Object-Oriented JavaScript, flexible, and more efficient code.
Nicholas C. Zakas thoroughly explores JavaScript’s
object-oriented nature, revealing the language’s ABOUT THE AUTHOR
unique implementation of inheritance and other key
characteristics. You’ll learn: Nicholas C. Zakas is a software engineer at Box and
is known for writing on and speaking about the latest
• The difference between primitive and reference in JavaScript best practices. He honed his experience
values during his five years at Yahoo!, where he was principal
• What makes JavaScript functions so unique frontend engineer for the Yahoo! home page. He is the
author of several books, including Maintainable JavaScript
• The various ways to create objects and Professional JavaScript for Web Developers.

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

$24.95 ($25.95 CDN)


PROGRAMMING/JAVASCRIPT
SHELVE IN:

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

Publisher: William Pollock


Production Editor: Serena Yang
Cover Illustration: Charlie Wylie
Interior Design: Octopod Studios
Developmental Editor: Jennifer Griffith-Delgado
Technical Reviewer: Angus Croll
Copyeditor: Rachel Monaghan
Compositor: Serena Yang
Proofreader: Elaine Merrill
Indexer: Nancy Guenther

For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly:

No Starch Press, Inc.


245 8th Street, San Francisco, CA 94103
phone: 415.863.9900; fax: 415.863.9950; info@nostarch.com; www.nostarch.com

Library of Congress Cataloging-in-Publication Data


Zakas, Nicholas C.
The principles of object-oriented JavaScript / by Nicholas C. Zakas.
pages cm
Includes index.
ISBN-13: 978-1-59327-540-2 (paperback)
ISBN-10: 1-59327-540-4 (paperback)
1. JavaScript (Computer program language) 2. Object-oriented programming languages. I. Title.
QA76.73.J39Z357 2014
005.1'17--dc23
2013048973

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
front­end 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).

About the Technical Reviewer


Originally from the UK, Angus Croll is now part of Twitter’s web frame-
work team in San Francisco and is the co-author and principal main-
tainer of Twitter’s open source Flight framework. He’s obsessed with
JavaScript and literature in equal measure and is a passionate advocate
for the greater involvement of artists and creative thinkers in software
development. Angus is a frequent speaker at conferences worldwide and
is currently working on two books for No Starch Press. He can be reached
on Twitter at @angustweets.
Brief Contents

Foreword by Cody Lindley . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Chapter 1: Primitive and Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 2: Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Chapter 3: Understanding Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Chapter 4: Constructors and Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Chapter 5: Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

Chapter 6: Object Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Conte nt s in De ta il

Foreword by Cody Lindley xiii

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

The name Nicholas Zakas is synonymous with


JavaScript development itself. I could ramble on
for pages with his professional accolades, but I am
not going to do that. Nicholas is well-known as a
highly skilled JavaScript developer and author, and
he needs no introduction. However, I would like to
offer some personal thoughts before praising the
contents of this book.
My relationship with Nicholas comes from years of studying his books,
reading his blog posts, watching him speak, and monitoring his Twitter
updates as a JavaScript pupil. We first met in person when I asked him
to speak at a jQuery conference several years ago. He treated the jQuery
community to a high-quality talk, and since then, we have spoken publicly
and privately over the Internet. In that time, I have come to admire him
as more than just a leader and developer in the JavaScript community.
His words are always gracious and thoughtful, his demeanor always kind.
His intent as a developer, speaker, and author is always to help, to edu-
cate, and to improve. When he speaks, you should listen, not just because
he is a JavaScript expert, but because his character rises above his profes-
sional status.
This book’s title and introduction make Nicholas’s intentions clear:
he has written it to help class-minded (that is, C++ or Java) programmers
transition to a language without classes. In the book, he explains how
encapsulation, aggregation, inheritance, and polymorphism can be
accomplished when writing JavaScript. This is the ideal text to bring a
knowledgeable programmer into the fold of object-oriented JavaScript
development. If you are reading this book as a developer from another
language, you are about to be treated to a concise and skillfully worded
JavaScript book.
However, this book also stands to serve programmers coming
from within the JavaScript fold. Many JavaScript developers have only
an ECMAScript 3 (ES3) understanding of objects, and they are in need
of a proper introduction to ECMAScript 5 (ES5) object features. This
book can serve as that introduction, bridging a knowledge gap between
ES3 objects and ES5 objects.
Now, you might be thinking, “Big deal. Several books have included
chapters or notes on the additions to JavaScript found in ES5.” Well, that
is true. However, I believe this to be the only book written to date that
focuses on the nature of objects by giving ES5 objects first-class citizen-
ship in the entire narrative. This book brings a cohesive introduction to
not only ES5 objects, but also the bits of ES3 that you need to grok while
learning many of the new additions found in ES5.
As an author myself, I strongly believe this is the one book, given its
focus on object-oriented principles and ES5 object updates, that needed
to be written as we await ES6 updates to scripting environments.

Cody Lindley (www.codylindley.com)


Author of JavaScript Enlightenment, DOM Enlightenment,
and jQuery Enlightenment
Boise, Idaho
December 16, 2013

xiv   Foreword
Acknowledgments

I’d like to thank Kate Matsudaira for convincing me that self-publishing


an ebook was the best way to get this information out. Without her advice,
I’d probably still be trying to figure out what I should do with the infor-
mation contained in this book.
Thanks to Rob Friesel for once again providing excellent feedback on
an early copy of this book, and Cody Lindley for his suggestions. Additional
thanks to Angus Croll for his technical review of the finished version—
his nitpicking made this book much better.
Thanks as well to Bill Pollock, whom I met at a conference and who
started the ball rolling on publishing this book.
Introduction

Most developers associate object-oriented


pro­gramming with languages that are typi-
cally taught in school, like C++ and Java,
which base object-oriented programming
around classes. Before you can do anything in
these languages, you need to ­create a class, even if
you’re just writing a simple command-line program.
Common design patterns in the industry ­reinforce class-based concepts
as well. But JavaScript doesn’t use classes, and this is part of the reason
people get confused when they try learning it after C++ or Java.
Object-oriented languages have several characteristics:
Encapsulation Data can be grouped together with functionality
that operates on that data. This, quite simply, is the definition of
an object.
Aggregation One object can reference another object.
Inheritance A newly created object has the same characteristics
as another object without explicitly duplicating its functionality.
Polymorphism One interface may be implemented by multiple
objects.
JavaScript has all these characteristics, though because the language
has no concept of classes, some aren’t implemented in quite the way you
might expect. At first glance, a JavaScript program might even look like
a procedural program you would write in C. If you can write a function
and pass it some variables, you have a working script that seemingly has
no objects. A closer look at the language, however, reveals the existence
of objects through the use of dot notation.
Many object-oriented languages use dot notation to access properties
and methods on objects, and JavaScript is syntactically the same. But in
JavaScript, you never need to write a class definition, import a package,
or include a header file. You just start coding with the data types that you
want, and you can group those together in any number of ways. You could
certainly write JavaScript in a procedural way, but its true power emerges
when you take advantage of its object-oriented nature. That’s what this
book is about.
Make no mistake: A lot of the concepts you may have learned in
more traditional object-oriented programming languages don’t neces-
sarily apply to JavaScript. While that often confuses beginners, as you
read, you’ll quickly find that JavaScript’s weakly typed nature allows
you to write less code to accomplish the same tasks as other languages.
You can just start coding without planning the classes that you need
ahead of time. Need an object with specific fields? Just create an ad hoc
object wherever you want. Did you forget to add a method to that object?
No problem—just add it later.
Inside these pages, you’ll learn the unique way that JavaScript
approaches object-oriented programming. Leave behind the notions
of classes and class-based inheritance and learn about prototype-based
inheritance and constructor functions that behave similarly. You’ll learn
how to create objects, define your own types, use inheritance, and other-
wise manipulate objects to get the most out of them. In short, you’ll learn
everything you need to know to understand and write JavaScript profes-
sionally. Enjoy!

Who This Book Is For


This book is intended as a guide for those who already understand object-
oriented programming but want to know exactly how the concept works in
JavaScript. Familiarity with Java, C#, or object-oriented programming in

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:

• Developers who are familiar with object-oriented programming con-


cepts and want to apply them to JavaScript
• Web application and Node.js developers trying to structure their code
more effectively
• Novice JavaScript developers trying to gain a deeper understanding
of the language

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.

Help and Support


If you have questions, comments, or other feedback about this book,
please visit the mailing list at http://groups.google.com/group/zakasbooks.

Introduction   xix
Primitive and
1
Reference T ypes

Most developers learn object-­oriented


­programming by working with class-
based languages such as Java or C#. When
these developers start ­learning Java­Script, they
get dis­oriented because Java­Script has no formal sup-
port for classes. Instead of defining classes from the
beginning, with JavaScript you can just write code
and create data structures as you need them. Because it lacks classes,
JavaScript also lacks class groupings such as packages. Whereas in
languages like Java, package and class names define both the types
of objects you use and the layout of files and folders in your project,
programming in JavaScript is like starting with a blank slate: You can
organize things any way you want. Some developers choose to mimic
structures from other languages, while others take advantage of Java­
Script’s flexibility to come up with something completely new. To the
uninitiated, this freedom of choice can be overwhelming, but once you
get used to it, you’ll find JavaScript to be an incredibly flexible language
that can adapt to your preferences quite easily.
To ease the transition from traditional object-oriented ­languages,
Java­Script makes objects the central part of the ­language. Almost all data
in JavaScript is either an object or accessed through objects. In fact, even
functions (which languages traditionally make you jump through hoops
to get references to) are represented as objects in Java­Script, which makes
them first-class functions.
Working with and understanding objects is key to understanding Java­
Script as a whole. You can create objects at any time and add or remove
properties from them whenever you want. In addition, Java­Script objects
are extremely flexible and have capabilities that create unique and inter-
esting patterns that are simply not possible in other languages.
This chapter focuses on how to identify and work with the two pri-
mary JavaScript data types: primitive types and reference types. Though
both are accessed through objects, they behave in different ways that are
important to understand.

What Are Types?


Although JavaScript has no concept of classes, it still uses two kinds of
types: primitive and reference. Primitive types are stored as simple data
types. Reference types are stored as objects, which are really just references
to locations in memory.
The tricky thing is that JavaScript lets you treat primitive types like
reference types in order to make the language more consistent for the
developer.
While other programming languages distinguish between primitive
and reference types by storing primitives on the stack and references in
the heap, JavaScript does away with this concept completely: It tracks
variables for a particular scope with a variable object. Primitive values are
stored directly on the variable object, while reference values are placed as
a pointer in the variable object, which serves as a reference to a location
in memory where the object is stored. However, as you’ll see later in this
chapter, primitive values and reference values behave quite differently
although they may initially seem the same.
Of course, there are other differences between primitive and refer-
ence types.

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

In JavaScript, as in many other languages, a variable holding a


primitive directly contains the primitive value (rather than a pointer to
an object). When you assign a primitive value to a variable, the value is
copied into that variable. This means that if you set one variable equal
to another, each variable gets its own copy of the data. For example:

var color1 = "red";


var color2 = color1;

Primitive and Reference Types   3


Here, color1 is assigned the value
of "red". The variable color2 is then Variable Object
assigned the value color1, which stores
"red" in color2. Even though color1 and color1 "red"
color2 contain the same value, they are
completely separate from each other,
color2 "red"
and you can change the value in color1
without affecting color2 and vice versa.
That’s because there are two different Figure 1-1: Variable object
storage locations, one for each variable.
Figure 1-1 illustrates the variable object
for this snippet of code.
Because each variable containing a primitive value uses its own
­storage space, changes to one variable are not reflected on the other.
For example:

var color1 = "red";


var color2 = color1;

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

Identifying Primitive Types


The best way to identify primitive types is with the typeof operator,
which works on any variable and returns a string indicating the type of
data. The typeof operator works well with strings, numbers, Booleans, and
undefined. The following shows the output when using typeof on different
primitive values:

console.log(typeof "Nicholas"); // "string"


console.log(typeof 10); // "number"
console.log(typeof 5.1); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"

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:

console.log(typeof null); // "object"

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:

console.log(value === null); // true or false

Compa ring W ithou t Coe rcion

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:

console.log("5" == 5); // true


console.log("5" === 5); // false

console.log(undefined == null); // true


console.log(undefined === null); // false

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.

Primitive and Reference Types   5


Primitive Methods
Despite the fact that they’re primitive types, strings, numbers, and
Booleans actually have methods. (The null and undefined types have
no methods.) Strings, in particular, have numerous methods to help
you work with them. For example:

var name = "Nicholas";


var lowercaseName = name.toLowerCase(); // convert to lowercase
var firstLetter = name.charAt(0); // get first character
var middleOfName = name.substring(2, 5); // get characters 2-4

var count = 10;


var fixedCount = count.toFixed(2); // convert to "10.00"
var hexCount = count.toString(16); // convert to "a"

var flag = true;


var stringFlag = flag.toString(); // convert to "true"

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 work­ing
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:

var object = new 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:

var object1 = new Object();


var object2 = object1;

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

Figure 1-3: Two variables pointing to one object

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.

Primitive and Reference Types   7


var object1 = new Object();

// do something

object1 = null; // dereference

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

Adding or Removing Properties


Another interesting aspect of objects in JavaScript is that you can add and
remove properties at any time. For example:

var object1 = new Object();


var object2 = object1;

object1.myCustomProperty = "Awesome!";
console.log(object2.myCustomProperty); // "Awesome!"

Here, myCustomProperty is added to object1 with a value of "Awesome!".


That property is also accessible on object2 because both object1 and
object2 point to the same object.

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.

In addition to generic object reference types, JavaScript has several


other built-in types that are at your disposal.

Instantiating Built-in Types


You’ve seen how to create and interact with generic objects created with
new Object(). The Object type is just one of a handful of built-in reference
types that JavaScript provides. The other built-in types are more special-
ized in their intended usage and can be instantiated at any time.
The built-in types are:
Array An ordered list of numerically indexed values
Date A date and time

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:

var items = new Array();


var now = new Date();
var error = new Error("Something bad happened.");
var func = new Function("console.log('Hi');");
var object = new Object();
var re = new RegExp("\\d+");

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 lit­erals, numeric
literals, Boolean literals, the null literal, and the undefined literal.)

Object and Array Literals


To create an object with object literal syntax, you can define the properties
of a new object inside braces. Properties are made up of an identifier or
string, a colon, and a value, with multiple properties separated by ­commas.
For example:

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

Primitive and Reference Types   9


This example is equivalent to the previous one despite the syntactic
differences. Both examples are also logically equivalent to the following:

var book = new Object();


book.name = "The Principles of Object-Oriented JavaScript";
book.year = 2014;

The outcome of each of the previous three examples is the same:


an object with two properties. The choice of pattern is up to you because
the functionality is ultimately the same.

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:

var colors = [ "red", "blue", "green" ];


console.log(colors[0]); // "red"

This code is equivalent to the following:

var colors = new Array("red", "blue", "green")


console.log(colors[0]); // "red"

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

var reflect = new Function("value", "return value;");

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.

Regular Expression Literals


JavaScript also has regular expression literals that allow you to define regu-
lar expressions without using the RegExp constructor. Regular expression
literals look very similar to regular expressions in Perl: The pattern is con-
tained between two slashes, and any additional options are single charac-
ters following the second slash. For example:

var numbers = /\d+/g;

// is the same as

var numbers = new RegExp("\\d+", "g");

The literal form of regular expressions in JavaScript is a bit easier


to deal with than the constructor form because you don’t need to worry
about escaping characters within strings. When using the RegExp con-
structor, you pass the pattern in as a string, so you have to escape any
backslashes. (That’s why \d is used in the literal and \\d is used in the
constructor.) Regular expression literals are preferred over the construc-
tor form in Java­Script except when the regular expression is being con-
structed dynamically from one or more strings.
That said, with the exception of Function, there really isn’t any right
or wrong way to instantiate built-in types. Many developers prefer literals,
while some prefer constructors. Choose whichever method you find more
comfortable to use.

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:

var array = [];


array.push(12345);

With bracket notation, the name of the method is now included in a


string enclosed by square brackets, as in this example:

var array = [];


array["push"](12345);

Primitive and Reference Types   11


This syntax is very useful when you want to dynamically decide which
property to access. For example, here bracket notation allows you to use a
variable instead of the string literal to specify the property to access.

var array = [];


var method = "push";
array[method](12345);

In this listing, the variable method has a value of "push", so push() is


called on the array. This capability is quite useful, as you’ll see through-
out this book. The point to remember is that, other than syntax, the
only difference—performance or otherwise—between dot notation and
bracket notation is that bracket notation allows you to use special char-
acters in property names. Developers tend to find dot notation easier
to read, so you’ll see it used more frequently than bracket notation.

Identifying Reference Types


A function is the easiest reference type to identify because when you use
the typeof operator on a function, the operator should return "function":

function reflect(value) {
return value;
}

console.log(typeof reflect); // "function"

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:

var items = [];


var object = {};

function reflect(value) {
return value;
}

console.log(items instanceof Array); // true


console.log(object instanceof Object); // true
console.log(reflect instanceof Function); // true

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:

var items = [];


var object = {};

function reflect(value) {
return value;
}

console.log(items instanceof Array); // true


console.log(items instanceof Object); // true
console.log(object instanceof Object); // true
console.log(object instanceof Array); // false
console.log(reflect instanceof Function); // true
console.log(reflect instanceof Object); // true

Each reference type is correctly identified as an instance of Object,


from which all reference types inherit.

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:

var items = [];

console.log(Array.isArray(items)); // true

Primitive and Reference Types   13


The Array.isArray() method is supported in most environments,
both in browsers and in Node.js. This method isn’t supported in Internet
Explorer 8 and earlier.

Primitive Wrapper Types


Perhaps one of the most confusing parts of JavaScript is the concept of
primitive wrapper types. There are three primitive wrapper types (String,
Number, and Boolean). These special reference types exist to make working
with primitive values as easy as working with objects. (It would be very
confusing if you had to use a different syntax or switch to a procedural
style just to get a substring of text.)
The primitive wrapper types are reference types that are automati-
cally created behind the scenes whenever strings, num­bers, or Booleans
are read. For example, in the first line of this listing, a primitive string
value is assigned to name. The second line treats name like an object and
calls charAt(0) using dot notation.

var name = "Nicholas";


var firstChar = name.charAt(0);
console.log(firstChar); // "N"

This is what happens behind the scenes:

// what the JavaScript engine does


var name = "Nicholas";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar); // "N"

Because the second line uses a string (a primitive) like an object,


the JavaScript engine creates an instance of String so that charAt(0) will
work. The String object exists only for one statement before it’s destroyed
(a process called autoboxing). To test this out, try adding a property to a
string as if it were a regular object:

var name = "Nicholas";


name.last = "Zakas";

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:

// what the JavaScript engine does


var name = "Nicholas";
var temp = new String(name);
temp.last = "Zakas";
temp = null; // temporary object destroyed

var temp = new String(name);


console.log(temp.last); // undefined
temp = null;

Instead of assigning a new property to a string, the code actually


c­ reates a new property on a temporary object that is then destroyed.
When you try to access that property later, a different object is temporar-
ily created and the new property doesn’t exist there. Although reference
values are created automatically for primitive values, when instanceof
checks for these types of values the result is false:

var name = "Nicholas";


var count = 10;
var found = false;

console.log(name instanceof String); // false


console.log(count instanceof Number); // false
console.log(found instanceof Boolean); // false

The instanceof operator returns false because a temporary object is


created only when a value is read. Because instanceof doesn’t actually read
anything, no temporary objects are created, and it tells us the ­values aren’t
instances of primitive wrapper types. You can create primitive wrapper
types manually, but there are certain side effects:

var name = new String("Nicholas");


var count = new Number(10);
var found = new Boolean(false);

console.log(typeof name); // "object"


console.log(typeof count); // "object"
console.log(typeof found); // "object"

As you can see, creating an instance of the primitive wrapper type


just creates another object, which means that typeof can’t identify the type
of data you intend to store.
In addition, you can’t use String, Number, and Boolean objects as you
would primitive values. For example, the following code uses a Boolean
object. The Boolean object is false, yet console.log("Found") still executes
because an object is always considered true inside a conditional statement.
It doesn’t matter that the object represents false; it’s an object, so it evalu-
ates to true.

Primitive and Reference Types   15


var found = new Boolean(false);

if (found) {
console.log("Found"); // this executes
}

Manually instantiating primitive wrappers can also be confusing in


other ways, so unless you find a special case where it makes sense to do
so, you should avoid it. Most of the time, using primitive wrapper objects
instead of primitives only leads to errors.

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

As discussed in Chapter 1, functions are


actually objects in JavaScript. The defining
characteristic of a function—what distin-
guishes it from any other object—is the pres-
ence of an internal property named [[Call]]. Inter­nal
properties are not accessible via code but rather
define the behavior of code as it executes. ECMAScript defines multiple
internal properties for objects in JavaScript, and these internal properties
are indicated by double-square-bracket notation.
The [[Call]] property is unique to functions and indicates that the
object can be executed. Because only functions have this property, the
typeof operator is defined by ECMAScript to return "function" for any
object with a [[Call]] property. That led to some confusion in the past,
because some browsers also included a [[Call]] property for regular
expressions, which were thus incorrectly identified as functions. All
browsers now behave the same, so typeof no longer identifies regular
expressions as functions.
This chapter discusses the various ways that functions are defined
and executed in JavaScript. Because functions are objects, they behave
differently than functions in other languages, and this behavior is central
to a good understanding of JavaScript.

Declarations vs. Expressions


There are actually two literal forms of functions. The first is a function
declaration, which begins with the function keyword and includes the name
of the function immediately following it. The contents of the function are
enclosed in braces, as shown in this declaration:

function add(num1, num2) {


return num1 + num2;
}

The second form is a function expression, which doesn’t require a name


after function. These functions are considered anonymous because the
function object itself has no name. Instead, function expressions are typi-
cally referenced via a variable or property, as in this expression:

var add = function(num1, num2) {


return num1 + num2;
};

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:

var result = add(5, 5);

function add(num1, num2) {


return num1 + num2;
}

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:

// how the JavaScript engine interprets the code


function add(num1, num2) {
return num1 + num2;
}

var result = add(5, 5);

Function hoisting happens only for function declarations because


the function name is known ahead of time. Function expressions, on the
other hand, cannot be hoisted because the functions can be referenced
only through a variable. So this code causes an error:

// error!
var result = add(5, 5);

var add = function(num1, num2) {


return num1 + num2;
};

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!");
}

sayHi(); // outputs "Hi!"

v var sayHi2 = sayHi;

sayHi2(); // outputs "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:

var sayHi = new Function("console.log(\"Hi!\");");

sayHi(); // outputs "Hi!"

var sayHi2 = sayHi;

sayHi2(); // outputs "Hi!"

The Function constructor makes it more explicit that sayHi can be


passed around just like any other object. When you keep in mind that
functions are objects, a lot of the behavior starts to make sense.
For instance, you can pass a function into another function as an
argument. The sort() method on JavaScript arrays accepts a comparison
function as an optional parameter. The comparison function is called
whenever two values in the array must be compared. If the first value is
smaller than the second, the comparison function must return a nega-
tive number. If the first value is larger than the second, the function
must return a positive number. If the two values are equal, the function
should return zero.
By default, sort() converts every item in an array to a string and then
performs a comparison. That means you can’t accurately sort an array
of numbers without specifying a comparison function. For example, you
need to include a comparison function to accurately sort an array of num-
bers, such as:

var numbers = [ 1, 5, 8, 4, 7, 10, 2, 6 ];


u numbers.sort(function(first, second) {
return first - second;
});

console.log(numbers); // "[1, 2, 4, 5, 6, 7, 8, 10]"

v numbers.sort();
console.log(numbers); // "[1, 10, 2, 4, 5, 6, 7, 8]"

In this example, the comparison function u that is passed into sort()


is actually a function expression. Note that there is no name for the func-
tion; it exists only as a reference that is passed into another function
(making it an anonymous function). Subtracting the two values returns
the correct result from the comparison function.

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 Java­Script 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.

On the other hand, JavaScript doesn’t ignore the named parameters


of a function either. The number of arguments a function expects is stored
on the function’s length property. Remember, a function is actually just an
object, so it can have properties. The length property indicates the func-
tion’s arity, or the number of parameters it expects. Knowing the function’s
arity is important in JavaScript because functions won’t throw an error if
you pass in too many or too few parameters.
Here’s a simple example using arguments and function arity; note that
the number of arguments passed to the function has no effect on the
reported arity:

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;

while (i < len) {


result += arguments[i];
i++;
}

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

sayMessage("Hello!"); // outputs "Default message"

If this were another language, the output of sayMessage("Hello!") would


likely be "Hello!". In JavaScript, however, when you define multiple func-
tions with the same name, the one that appears last in your code wins.
The earlier function declarations are completely removed, and the last
is the one that is used. Once again, it helps to think about this situation
using objects:

var sayMessage = new Function("message", "console.log(message);");

sayMessage = new Function("console.log(\"Default message\");");

sayMessage("Hello!"); // outputs "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);
}

sayMessage("Hello!"); // outputs "Hello!"

In this example, the sayMessage() function behaves differently based


on the number of parameters that were passed in. If no parameters
are passed in (arguments.length === 0), then a default message is used.
Otherwise, the first parameter is used as the message. This is a little more
involved than function overloading in other languages, but the end result
is the same. If you really want to check for different data types, you can
use typeof and instanceof.

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

person.sayName(); // outputs "Nicholas"

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 Scribd Document
with Unrelated Content
Lawrence cut some fowl and bacon, adding vegetables, and filled a
small tumbler with red wine, and then, stepping to the door of the
berth in which Lucy Acton was confined, he almost noiselessly
inserted the key and softly shot the latch, and resumed his seat, and
Paul, bearing the tray of food, knocked on the door, and receiving no
reply entered, and the motion of the ship upon a long, steady heave
of swell slammed the door to after him.
Mr Lawrence, with his back turned upon this cabin door, heard
Lucy's voice, but not what she said. If Paul answered her his voice
was so sunk by the awfulness of her presence, by all that she meant
being at sea, by all that she had typified to this forlorn vagrant when
on shore, that his accents were inaudible in the cabin.
After a few minutes he came out. He approached the cabin table
and stood close. His face wore a mingled look of astonishment and
fear, and he was very pale. He was as grotesque as something
fanciful in a fairy story, with his red hair, hump, long arms, rounded
legs, and whilst he stood he scratched himself as a monkey does.
His chin was enormous, and out of all proportion to his face.
"Is Miss Acton eating her dinner?"
"No, sir."
"What did she say to you?"
"Why, your honour, when I went in she looked at me and burst into
a laugh that turned my blood cold."
"She didn't know you to be the man that gave her the letter that
brought her here?"
"She didn't look as if she remembered me, your honour, and she said
nothing about it."
"What did she say?"
"Why, your honour, she says whilst I hold the tray, 'What are you?'
'I'm the ship's steward, your ledyship,' says I. 'Ay, but what else?'
says she. 'What forest was you caught in?' I didn't understand her,
sir, and didn't answer. 'Do you come from Africa?' says she, 'or have
you broke loose from a travelling wild beast show?'"
Mr Lawrence arched his eyebrows. Certainly he did not recognise the
sweet and sympathetic Lucy Acton in these questions.
"And then she says, frowning as though she'd up with a knife off the
tray and run it into me, 'What have you got there?' 'Your dinner, your
ledyship,' says I. 'Put it down upon the floor!' says she in a sort of
shriek, as if she was trying to sing. 'Don't you see I'm in tatters?
They've got me here who am a princess at home, and these are my
rags and all I've got,' says she, spreading her dress with her hands
as though she was goin' to skip. 'Beggars in rags feed on the floor:
they feed so. Anywhere's good enough for them. I've seen 'em
sitting on the edge of ditches eating. Put the food on the floor!
That's how princesses in tatters dine.' I did as I was ordered, your
honour, and came away."
"Go in presently and see if she's done, and ask if she'll have some
fruit pie or cake, and report if the tray is still on the deck."
"Yes, sir," answered Paul, who was not sailor enough to say, "Ay, ay,
sir," which should have been his speech.
Mr Lawrence was exceedingly thoughtful. What opinion he was
arriving at, whether he was beginning to think that the girl was
really mad or that she was merely acting with extravagant absurdity
in the hope of disgusting him, you could not have told by looking at
his face.
In about ten minutes after Paul had made his report, Mr Lawrence
told him to knock on Miss Acton's cabin door and enter. This time the
door swung to and fro, and Mr Lawrence, who had turned in his seat
to follow the steward's movements, saw Miss Acton upon all fours
upon the deck with her face close to the tray, as though she was
taking up the food with her mouth. A swing of the vessel hove the
door to its latch, and hid the extraordinary picture.
A minute or two later Paul came out, shutting the door after him.
"I saw her," said Mr Lawrence. "She is on her hands and knees.
What did you say?"
"I asked her if she'd have some fruit pie or cake. She didn't look up
nor answer. She's chucked most of what I took in about the cabin."
"She has made no meal, then?"
"I couldn't tell, your honour. The piece of chicken is on the bed, and
I see the piece of bacon under it. I dunno what she was doin' with
her nose a-nuzzling of the tray as though she was a-smelling of the
salt."
"Don't enter the cabin for half an hour. Then go in and clear up. And
if she speaks, make no answer, and take no notice of her, but clean
up the mess."
He left the table, and turned the key softly in Lucy's door, withdrew
it, and went on deck. The breeze that had blown the Minorca out of
Old Harbour still sang in her shrouds, but with a fresh and a
stronger song. The sea ran in lines of brine which flashed friskily.
The mountainous clouds sailed down the blue heavens with the
solemn majesty of line-of-battle ships draped in sun-empearled cloth
from truck to waterway. The bluff-bowed barque was darting foam
from her to right and left as she thrust through the streaming waters
and rolled with dignity, slowly to leeward and yet more slowly to
windward as she brought the violet shadowed cavities of her canvas
to the wind. The hens were noisy in their coops, and cocks crew.
The sound of waters broken and in motion was musical. The
shadows of the rigging slided gently to and fro over the wide
breadth of white planks. The men in the picturesque garb of the
merchant sailor of that day, some of them in striped pantaloons
flowing to the shoe, some in short-cut blue jackets, and most of
them in round hats, were distributed over several parts of the ship.
Mr Eagle walked the weather side of the quarterdeck. In reply to Mr
Lawrence's question, he said that nothing had been in sight and
nothing was in sight. This Mr Lawrence verified by a searching
sweep of his gaze round the horizon, and Mr Eagle went below into
the cabin to eat his dinner.
When he was there he bade Paul go forward and tell Mr Pledge that
dinner awaited him. This privilege was Pledge's because, though he
was the ship's boatswain and also her carpenter, he kept watch and
headed the starboard division of the crew as second mate.
He was a tall, lank man, rather knock-kneed, with a long neck, and,
which was very unusual in those days, his chin was garnished with a
quantity of straggling reddish hair. His face looked as though it had
been put together without much judgment. His nose, which was
broken, was not in line; his mouth was somewhat on one side, one
eyebrow was raised and the other depressed. His eyes were small,
of a deep, moist, soft blue. He had served in the American Navy, and
had much to tell about Yankee captains and commodores. He was
dressed in the garb of the common sailor, and it is not wonderful
that Mr Lawrence should decline to meet him at table, which, if it did
not make their footing equal, must bring them into relations the
fastidious, haughty, handsome naval officer would regard in an
uncommon degree objectionable.
He entered the cabin and took his place. Mr Eagle at the foot of the
table carved the boiled beef. When they were fairly under way with
their dinner Paul went forward, and the two men were alone in the
cabin, out of hearing of Mr Lawrence's ears through the open
skylight if they suppressed their voices, equally out of hearing of the
inmate, under lock and key, of the captain's cabin.
Though Mr Lawrence had communicated the intelligence of the girl
being on board and of his holding sealed orders from Captain Acton
in confidence to Mr Eagle, the sensations excited in this plain and
acid sailor by the extraordinary, astounding, and unexpected
revelations had filled him to bursting point with a fever and passion
for giving the news. In short, the man's mind was much too small to
retain what had been poured into it, and of course it overflowed. To
whom other than Tom Pledge could he speak? Pledge and he had
sailed in Captain Acton's employ for two or three voyages; they were
friends, and visited each other ashore where each had a little
cottage and a wife. So after a careful survey of the skylight, which
lay open just above the table, and a cautious look round, Mr Eagle
said: "Tom, did you observe me and the Capt'n walkin' up and down
this morning in conversation?"
"Ay," answered Pledge, "and I wondered what there was between ye
to keep ye so busy in talk."
Mr Eagle again looked up at the skylight, and said as softly as his
gruff voice permitted: "What d'ye think, Tom, of our sailin' under
sealed orders from Captain Acton which the Captain's to read in
latitood twenty north and longitood thirty west? The contents of
them sealed orders aren't exactly known to the Capt'n, but he told
me from what Capt'n Acton let fall, he believed that the ship was to
be carried to another port, and there handed over to a Spanish gent
as was a-waitin' to receive her, and that the whole ship's company
was to be discharged and sent 'ome at Captain Acton's expense and
the wages they had agreed for trebled. What d'ye say to that?"
Pledge, who chewed slowly as a cow the cud, watched his
companion steadfastly, his temples throbbing with the action of his
jaws, and said: "Do you believe it, John?"
"So help me God, yes, then, as I sit here," answered Mr Eagle.
"Who is to work the ship for him?" asked Pledge. "For you may
depend upon it that if the crew are to be carried away to an
unbeknown place, they'll all go below to a man, for Jack's as good
as his master when it comes to his having to do something which he
didn't agree for."
"I put it as you do, though in different words," said Mr Eagle, "and
he answered that Captain Acton's orders must be obeyed, that the
crew's refusal would be mutiny, and that if they wouldn't work the
ship to a port, where he could ship a fresh crew, he'd heave a-back
the main-topsail yard and wait for a man-o'-war to come along."
"Well, I'm jiggered!" said Mr Pledge, now looking slightly startled, for
he was an old sailor, he well understood the despotic powers of the
captain of a ship, and he readily perceived that Mr Lawrence's
threats in case of refusal by the crew were to be carried out.
"But that's not all," continued Mr Eagle, with another glance at the
skylight. "It ain't even 'arf all, and I think you'll agree with me that
the rummiest part's got to come."
"Another slice, John!" said Pledge, pushing his plate, and cutting a
big chunk from a loaf.
"Who d'ye think's aboard?"
"Who?"
"Why, Captain Acton's daughter, Miss Lucy Acton!"
"What's she a-doing' of here?" enquired Pledge, pulling away his
plate heavy with meat and fat.
"She's a-running away with Mr Lawrence!"
"Or is Mr Lawrence a-running away with her?"
"According to his yarn," said Eagle with sour solemnity, "they've
rooned away with each other."
"Where is she?" asked Pledge.
Eagle dumbly pointed to the Captain's cabin. "It's an artfully laid
plot," said he, "if the Capt'n's to be believed. She's supposed to be
locked up agin her will. By-and-by she's to go among the sailors and
swear that she's been carried off by violence. This is to make her
father believe that she never consented to run away, as she don't
want to lose the fortune as 'ud otherwise come to her."
"Wasn't there some talk a bit of a time past of him a-courting of
her?" said Pledge.
"Why, yes, now that you remind me, I recollect."
"Well, John," said Pledge, "it's not for me nor the likes of me to
interfere in such a galavantin' job as this. If the young lady's been
run away with with her own consent, it's not for me, I says, to pay
any attention to what's 'appening. People who fall in love with each
other and are objected to by their relatives will sometimes carry on
their business in a way as might make pious, respectable old
parients feel their hair standing short up on their heads. I've lived
long enough in this 'ere world to descover that no good ever comes
to a man by messing about in other people's consarns. But when it
comes to this ship being navigated to another port than the one
agreed for, why, naturally you set me a-thinking, John. I don't know
nothing about them sealed orders you refer to, but it seemed
strange to me when I heard of it, and it's strange to me still, that Mr
Lawrence should have been chosen to command this vessel when
the berth was yourn by right of sarvice. Was it because Captain
Acton couldn't be sure of your a-executing his wishes? What d'ye
think yourself, John? You've got to consider it's two naval officers
acting together; they know each other's mind, and I guess that
when Captain Acton chose Mr Lawrence to take charge of his ship he
knew that he was in the 'ands of a man who'd listen to no talk, who
was used to man-o'-war's discipline, and would act if it came to
having to shoot men down so as to gain his ends."
Mr Eagle, whose views were undoubtedly in accord with Mr Pledge's,
viewed his companion in acid silence.
Just about this time the steward Paul came down the companion
steps with the cabin key which he had received from Mr Lawrence.
He took no notice of the two men seated at the table, but stepped
to Lucy's door, knocked, paused, inserted the key, and passed in. He
emerged in less than two minutes holding the tray that was covered
literally with broken victuals, and locking the door was about to step
up the companion ladder when Mr Pledge said: "Who've you got
locked up in that there cabin?"
"You must ask the Captain that, sir, if you want to know," Paul
answered.
"You dog! D'ye know I'm second mate? Answer me, or I'll flay ye
before sundown," said Pledge, turning scarlet.
"I durs'nt," whined Paul. "I've the Captain's orders to keep my
mouth shut," and he hastened up the steps.
He was followed by Mr Eagle, who thought it about time to relieve
the Captain.
Mr Pledge had eaten his last morsel of cheese and was leaving the
table, when his attention was arrested by a knocking on Lucy's door,
accompanied by the cries of a female; but what she said he could
not hear. So Mr Pledge, taking some steps, stood close to the door.
The voice of Lucy within cried out: "Is anybody there?"
"I'm here, ma'am," answered Pledge.
"Who are you?"
"I'm Thomas Pledge, acting second mate of this 'ere ship, ma'am."
"Open this door!"
"I can't, ma'am, it's locked," and in proof of his assurance, Pledge
turned the handle and shook the door.
"I demand to be set at liberty!" cried Lucy, in the strained, wild voice
that had frightened the hunchback steward. "The villain who
commands this ship lured me into her by pretending that Captain
Acton, who is my father and the owner of the vessel, lay seriously
injured through an accident, and wished to see me. I demand to be
returned to my home! I have been stolen away by a base artifice.
The crew of this ship are the servants of my father, and they would
know his wish must be to recover me, and your duty, and Mr Eagle's,
and the men's, is to turn the ship for Old Harbour, and surrender me
up to my father. If this is not done I shall go mad. I am mad now.
The wretch who by a lie has seduced me into this vessel, has driven
me crazy."
And with that she fell to singing, from which she broke off after a
few moments to burst into a shrieking, lunatic laugh.
Thomas Pledge's mind was of a very common order. He had
gathered from Eagle that the girl was to pretend a situation of acute
distress, that when she was married her father should not hold her
responsible for her elopement. Her words might have carried weight,
and even conviction, but for the song and loud unmeaning laugh
that closed them, in which Mr Pledge saw nothing but acting, not
having experience of insanity in any shape or form. And shouting
through the door, "I'll go and report to the Captain, ma'am, that
you're locked up and want to get out," he turned, with the intention
of making for the companion ladder, when he saw Mr Lawrence
standing a few paces abaft the steps, tall, stern, frowning, his face
fierce with the strain, and indeed almost fury, of the attention with
which he had bent his ears to catch the syllables of Lucy through the
bulkhead.
Mr Pledge started like a guilty thing surprised.
"What are you doing at that cabin door, sir?" asked Mr Lawrence. "I
do not enquire what you are doing in this cabin, for, according to the
custom of this ship, and perhaps of others in your Service, you take
your meals here. But what are you doing at that door, conversing
through it with the lady inside?"
"The lady thumped and I went to see what was the matter, sir," said
Mr Pledge, awed in his old man-o'-war instincts by the over-bearing,
I may say, the overwhelming demeanour of Mr Lawrence, which was
to his words as the thunder of the explosion is to the message of the
firearm.
"Has Mr Eagle been talking to you about the subject of our
conversation this morning?" said Mr Lawrence.
Now, Tom was too sound a shipmate to betray John. He answered
doggedly, as though Mr Lawrence as well as himself must be aware
that he was trespassing on ground he had no right to tread: "We
yarned of course together. We've sailed together afore, and can
always find something to talk about, sir."
Mr Lawrence seemed to read the man's thoughts. Unscrupulous as
was this Naval gentleman, he was an extremely clever fellow.
Preserving a severe austerity of countenance, a demeanour upon
which the word discipline was writ large, he exclaimed: "It is not my
intention to ask you if Mr Eagle has broken his faith with me and
communicated to you the confidence I imparted to him this morning.
You are, sir, by virtue of your rank aboard the ship free of this cabin,
and it is therefore desirable that I should trust you. The lady in
yonder berth is Miss Lucy Acton, who consented to elope with me,
providing it should be understood by all on board that she was being
kidnapped or stolen from her home. That this should appear, it was
arranged between us that she should be locked up as though she
were a prisoner, and then in a day or two I should enlarge her, and
she would go amongst the crew and speak of my cunning and
stratagem, and her desperate lot in being torn from her father's
home. All which would in due course reach her father's ears, and
mollify his wrath at her giving me her hand in the existing state of
my fortunes, and preserve to her the fortune she must inherit as
Captain Acton's only child. Now, sir," continued Mr Lawrence in his
frowning, imperious way, "this is submitted to you in confidence, and
it is manifestly my wish that some of the crew should credit her
story that they may give the evidence we desire when they are
called upon to tell what they know!"
"Well, sir," answered Mr Pledge, pleased by the skipper's candour
and condescension, "it's not for a plain sailor man like me to put his
hand into such a tar-bucket as this. I know my bit, and I'm a-willing
for to do it, and if the hands get to hear the story of the lady it'll
come from her or from that there humpbacked steward who waits
upon her, and not from me, for I'm for minding my own affairs, and
sticking like a barnacle to a ship's bottom to the ondertakings I enter
into."
He said this with a grave nod of the head, that the significance of
the closing passage of his speech might be mastered, for it was then
running through his mind that more lay behind the presence of Lucy
Acton on board than Mr Lawrence suspected he knew: by which he
referred to the sealed orders.
Mr Lawrence made no answer, and Mr Pledge seeing that he was to
go, went on deck by the only exit, namely, the companion ladder.
Immediately after he had passed through the hatch the steward Paul
descended.
"Did you clear away the mess from Miss Acton's berth?" asked Mr
Lawrence.
"Yes, sir."
"The lady, I presume, ate nothing?"
"I couldn't see that she had, your honour."
"When you have cleared this table, go forward and tell the cook to
cut a plate of the most delicate beef and chicken sandwiches he can
contrive. Get a bottle of red wine and a glass, and be ready to carry
the refreshments to the lady when I've left her."
He approached Miss Acton's door. Lucy was seated on a locker under
a window, three of which embellished the stern of the Minorca. The
ocean as the ship lightly depressed her stern, was visible through
this window, a blue field decked with flowers of foam that rose and
sank. The large glazed space filled the cabin with light, which
trembled with the pulse of the white wake streaming fan-wise, and
with the shivering of the sunlight into splinters of diamond brilliance
by the fretful motions of the breeze-brushed waters.
Miss Lucy Acton sat with her eyes veiled by downcast lids fixed in a
stare as lifeless as the dead upon her hands, which lay clasped in
her lap. So motionless was she, you would have said she slept. Much
of the lovely bloom that always gave to her lineaments a choice
sweetness was absent, but not the less did as much of her face as
was visible express its refined and delicate beauty.
When Mr Lawrence entered she did not raise her eyes, nor whilst he
stood looking at her did she discover by any sort of movement the
least knowledge of his presence.
"Lucy!" he said, speaking the word in the wooing voice of love.
She made no sign. He repeated her name as though startled by her
immobility in which an element of tragedy might have been found in
the singular, unwinking fixity of her stare upon her hands. He
stepped to her side, and peered closely into her face and listened to
hear if she breathed. Oh yes: she breathed, she was alive. But
though he put his face so close to her's that she might have felt his
breath upon her cheek, her form did not move by so much as might
indicate the passage of a thrill, her eyes remained as steadfast in
their gaze as though they were painted.
He withdrew a step, and exclaimed: "Lucy, why will you not speak to
me? Why will you not look at me? You know that all this is done in
the holy name of love, and God who knows me knows that I would
not cause you a pang, that your beautiful eyes should not be
shadowed by a tear drawn by any action of mine if I could have
believed that loving me as I know you do, that loving you as you
know I do, you would have come to me at the summons of my
passion, and hand in hand with me as my wife, taken your chance of
all that might have followed."
The emotion of an impassioned heart, the melody of a rich and
manly voice were in his words, and no man, though he should hate
the fellow for his wrong-doing, could have doubted his sincerity
whilst listening to his speech. Add to this his superb figure, his
handsome face glowing with feeling, the hereditary dignity of his
demeanour; but these were expressions of his meaning which she
would not raise her eyes to witness.
All on a sudden and when the silence that followed had not lasted
ten seconds, she sprang to her feet with a shriek; she dashed her
hands to her face, she rushed as though pursued to the other end of
the cabin, and there crouched with her face to the bulkhead, hidden
in her hands; and thus she stood rocking herself sideways, moaning:
"Why am I not sent home? Why am I here a prisoner? What will my
father think has become of me? Home, home, home! In the hands of
a man that dare rob his employer! At the mercy of one who of all
Captain Acton's friends and acquaintances should feel the most
deeply obliged to him." She wheeled round and out of her
incommunicable attitude and language of distress, and said, looking
at him vacantly with a cold, pale smile: "Are you Mr Lawrence, the
son of Sir William Lawrence, Captain Acton's friend?"
"You know, madam, that I am," he answered, bowing with graceful
suavity, and with a light smile that was like saying, "I understand the
import of your tactics, and am willing to wait and watch you."
"I know, sir," she exclaimed with the vehement indignation and
contempt conveyed by that perfection of art which conceals art and
which is a gift of intuition beyond the reach of those not born with it,
"that Sir William Lawrence has a son, and that he was dismissed
from the Navy for a brutal, drunken outrage of which he alone, of all
the gentlemen and officers in the Service, was capable."
He coloured brightly at this, and his frown was as though a shadow
had come between him and the light that revealed his face.
"I know," she continued, still preserving her accent of scorn and
viewing him with eyes that did not seem to be her's, so did she
contrive to diminish the breadth of the beauty of the lids, so did she
manage to look passions and feelings which the memory of her
oldest friend could never have recalled as vitalising her brooding
half-hooded gaze: "I know that this man came ashore and lived
upon his father who was poor, and drank and gambled until his
name provoked nothing but a shrug, and that one day in a fit of pity,
for which doubtless he has asked God's pardon, Captain Acton, who
loves Admiral Lawrence, gave his poor creature of a son command
of a ship. This I know," she said, letting her eyes fall suddenly from
his face down upon her fingers, which she seemed to count as she
proceeded. "But I had always supposed that there was some spirit of
goodness left in Mr Walter Lawrence. I believed that though he
might gamble and drink and live in idleness upon the bounty of his
father, he with all his imperfections was a man incapable of
outraging the feelings of a young girl, incapable of betraying the
generous confidence of one who stood to him as a warm-hearted
friend. Can you be that Mr Lawrence?" she said, peering at him in
such a peculiar fashion, with such archness of contempt that a
spectator, short-sighted and at a little distance, would have
supposed she was looking at the handsome fellow through an eye-
glass. "Oh, I am going mad to suppose it—mad to think it possible!"
She flashed her hands to her forehead, sobs seemed to shake her,
she turned on her heel and went to the big stern window, and
looked out upon the sea.
He seemed to have been struck dumb by the fury of her candour.
His teeth were fastened upon his under lip, his cheek had grown
pale.
"Will you leave this cabin," she said without turning, "and acquaint
the first ship you meet with that you have a young gentlewoman on
board who desires to be set ashore in England? I do not ask you,"
she continued, with the cutting sneer that was on her lip as plain in
her voice as though her face was visible to him, "to return this ship
and her contents to their lawful owner. But if you suppose that you
are going to gain me by keeping me a prisoner in this den, if you
imagine that all the horror which my soul can feel for a wicked,
unscrupulous man is not likely to be with me in all thoughts of you
that come to me with your presence, or fill me with madness when I
am alone, then better for you if you should go to the stack of
muskets which is in the cabin, load one and shoot yourself."
And clapping her hands as though she was in the box of a theatre
ravished by some transcendently fine performance, she once more
delivered herself of the maniac laugh which had curdled Paul's blood
and which though ringing from lips, though proceeding from a face
hidden from him, seemed to strike Mr Lawrence as nothing which
she had spoken had, and save but for the swaying of the ship he
stood as motionless as a statue facing another statue whose back
was turned to him.
CHAPTER XII
MR LAWRENCE REFLECTS

When Mr Lawrence found that nothing he could say, nothing he


could implore, nothing he could entreat his companion to forgive,
provoked Lucy into looking round from the window through which
she gazed at the sea, nor caused her to alter her posture, which
curiously suggested with dramatic art that she was alone, that the
man was gone, that she was engrossed by thoughts of her own, he
withdrew. After closing the door he seemed to hesitate over turning
the key, but turned it nevertheless and pocketed it as before.
The cabin was empty. Mr Pledge was again superintending work
forward. Mr Eagle kept the look-out. This was the ship's first day
from home. The watches had not been set, and it would be "all
hands" with the ship's company until the second dog-watch came
round. The vessel swayed on the heave of the swell with the
ponderosity, you would have looked for in one of her mould. She
creaked in every timber. She pitched rapidly, albeit the blue
afternoon hollow was very shallow, but the sullenness of the sturdy
round bows was in her longwise motion. If Lucy meant to be sea-
sick she was neglecting her chance, for here was movement more
fitted to discompose the land-going stomach than the lofty billow
that is swung by the storm. But so far this sweet and amazing young
lady had proved herself as good a sailor as Mr Lawrence himself.
Whilst he stood in reflection at the cabin table, the steward Paul
came down the steps bearing a tray of refreshments so prettily
decorated as to prove that the ship's cook had been chosen with
judgment. The pyramid of sandwiches might have kindled a light in
the dulled eye of one lying oppressed with nausea. In addition were
a plate of cold tongue, a small plate of brawn, with two or three
other delicacies. On the tray stood a bottle of red wine and a
tumbler. Mr Lawrence told Paul, handing him the key as he gave him
the directions, to take the tray to Miss Acton, place it on the table in
perfect silence, and quit the cabin, making no answer if she spoke to
him. When this was done and the key received by Mr Lawrence, he
took a tumbler from a rack out of the skylight and entered the berth
which under the name of "sick-bay" had been fitted up for his own
use. Here he contrived to find a bottle of brandy, a small caulker of
which without water he swallowed.
This interior presented a very inhospitable look; its rough-hewn
bunks might have been intended for the accommodation of
prisoners. The deck was without carpet. Indeed the only colour or
warmth which this melancholy hole presented to the eye or the mind
was to be found in such wearing apparel as swung from hooks, in Mr
Lawrence's sea-chest, in the nautical instruments, in the shelves
with their little burden of tin box, a few books, and so forth.
He sat down upon his chest, folded his arms and sank into thought.
Had he needed a motto for his reflections he might have found one
in the Duke of Gloster's speech:
"Was ever woman in this humour woo'd?
Was ever woman in this humour won?"

He had been so transported by his scheme for winning the beautiful


young girl whom he worshipped that his survey of the vast canvas of
his intentions was in reality restricted to but one corner of it, so that
he saw only a little of the whole truth. First, and certainly foremost,
he had counted upon her love for him, which, however carefully the
secret might have been kept by her, was witnessed by him every
time they had met, and flourished as a conviction in him. He had
looked for her forgiveness for the rashness, and, it may be added,
the cruelty of his conspiracy of love, and he never could have
believed that in the sweet image of the girl dwelt such a character
as she had exhibited since, after inveigling her on board into his
cabin, he confessed that the story which had brought her to him was
a lie, and with a face filled with the light of worship for her avowed
his intentions.
In some strokes of this character he might have indeed believed that
she was merely acting, but other features had impressed him to
such a degree that, though he was determined—not yet, perhaps—
to accept the suspicion, or the persuasion of his own opinion, he,
behind the darkest curtains of his heart, felt a fear that his
stratagem would force her reason from her brain, that she would go
mad when she clearly understood that the ship was bound to Rio to
be feloniously sold there, when she realised that she had been
ruthlessly torn from her father, from her home, and all that she
loved, and that her name must ever bear the stain, happen what
might, of Mr Lawrence's ignoble feat of abduction.
But as a rule men who act with excessive imprudence are endowed
with a quality of self-complacency which enables them to persuade
themselves that "it's all right," and to this belief they cling until time
and experiment prove that it's all wrong; whereupon their moral
being falls to pieces, they become mean, cheap, and weak, and
bewail their folly under the name of misfortune.
Mr Lawrence having meditated awhile, rose from his chest,
unclasped his arms, and whistling softly the familiar air of "Wapping
Old Stairs," quitted his naked, forlorn, inhospitable berth.
As he advanced towards the companion steps the hatch was
darkened by the figure of Mr Eagle, who, on catching sight of the
Captain, cried: "A sail broad on the larboard bow, sir!"
Mr Lawrence rushed back to his cabin, whence he took from a shelf
a telescope of uncommon power for those times, the gift of no less a
man than Captain Acton after intelligence had been brought to him
of a particular heroic piece of behaviour on the part of Mr Lawrence.
With this telescope he sprang on to the deck, and levelling it at the
sea over the lee bow, viewed in the lenses the picture of a large
man-of-war with two white bands broken by gun-ports. She was far
away, yet not so distant but that a hand's breadth of her black side
could be seen shivering in mirage betwixt the lower white band and
the wool-white tremble of water running aft. All the men of the
Minorca were on deck at work here and there. They looked at Mr
Lawrence as with levelled telescope he stood on the quarterdeck
viewing the distant battleship. They all belonged to Old Harbour
Town; all had heard of him, and a few knew him by sight. They were
members of a group of inhabitants who felt that the presence
amongst them of a man whose sea story though brief was brilliant
did them and Old Harbour Town honour, and they regarded him as
he stood with the glass at his eye, as though they should say, "Yon's
a man-o'-war, and she may be a Johnny; but there's the Jack who
will know what to do with her." And, may be, some of those who
thus reflected cast their eyes upon the figure of Mr Eagle, who stood
near enough to the Captain to enable the sight to master the details
of a very striking contrast.
"Hoist the ensign!" exclaimed Mr Lawrence.
Mr Eagle, breaking into a run, sent aloft at the peak of the barque
the meteor flag of Old England.
"British!" said Mr Lawrence in a moment, as though speaking to
himself, "as I thought," holding the man-o'-war in view in his
telescope, and marking the slow soaring of the British flag to the
gaff-end of the two-decker.
The Captain's exclamation had been overheard, and the gaze of the
Merchant seamen of the Minorca was fixed upon the figure of one of
those fabrics which could never light up with their cloud of sail the
confines of the sea or the nearer fields of water, without exciting a
thrill of interest or causing the heart to leap up in momentary
transport of patriotic pride. She was under fore and mizzen jury
topmasts. With the main all was well, and the spars lifted their
canvas to the moon-like royal without hint of wreck or suggestion of
wound. Either she had been in action and had come away crippled,
or had been in trouble on a lee-shore or amongst rocks. And still she
painted a stately and a swelling picture upon the blue sky past her.
The sun was westering; his yellow light flung upon the distant
canvas the delicate sheen of fine silk. From the hand's breadth of
black side under the lower white band, the stately roll to leeward
flashed lightning-sparks from the wet, and, as she slightly pitched,
the upheaval of her bows exhibited at the fore-foot the snow-like
crumbling of foam. She passed in grandeur and in tranquillity.
All the hearts aboard the Minorca, British as they were, must wish
that that gallant show might not fall in with something superior to
herself in weight of broadside and perfect in equipment aloft.
Though every man felt that the sequel of such a rencountre must be
the inevitable one: that is the sailing of the jury-rigged two-decker in
company with a powerful prize both bound, let us suppose, for the
sweet and lovely waters of Plymouth Haven.
Mr Eagle approached Mr Lawrence, who turned upon him suddenly.
"The sails of that ship," cried the Captain, "must have been in sight
some time before you reported her. When I came on deck she was
hull up. Is this your idea of keeping a look-out?"
"I reported her as soon as I saw her, sir."
"Wasn't she reported from the masthead?"
"Yes, sir, and then I saw her and reported her to you."
"And this is the way that a look-out is to be kept aboard this ship,"
said Mr Lawrence with a biting insolence of scorn, and that sort of
pity which enrages more than kicks or execrations. "If you don't hold
to the instructions you receive from me, sir, you'll soon find yourself
eating black bread in a French dungeon with straw from a sty for a
bed."
He made a step to the ship's side, and the mate without answer
slunk away to leeward.
About this time the breeze began to freshen. The horizon slightly
thickened with some windy change in the atmosphere and with the
shadow of the evening. The Minorca under all plain sail heeled into
the white smother of spume alongside, and as she sprang crushed
the surge with her round weather-bow till the bright brine
sometimes leapt like a fountain athwart the forecastle. Mr Lawrence
watched her behaviour with attention, and often sent a look at the
creaming road of wake which was so brilliant and long that, as the
shadow deepened, the tail of it was lost to view.
In the second dog-watch the crew were mustered aft and divided
into watches. It was tolerably certain that down to this moment no
hint had found its way amongst them that their course would
presently be for any other port in the world than Kingston.
Mr Lawrence supped alone as he had dined alone, and, as he
intended, to breakfast alone. At sea the last meal which in the old
forecastle days consisted of black tea and ship's biscuit was
invariably called supper. At six o'clock Mr Lawrence sat down to the
last meal of the day. A tray for the inmate of the Captain's cabin was
prepared. It was furnished with tea and milk (for the ship was but
one day out, and though she wanted a cow she could not need at
least a day's supply of milk), bread and butter, slices of ham and
biscuits. When the steward came from the cabin Mr Lawrence said:
"Did the young lady speak?"
"No, sir."
"What is she doing?"
"She is pulling feathers and other stuff out of her bed which she has
drawed from its place on to the deck, and she is sitting alongside of
it a-fluffing of the feathers over the cabin floor."
"Did she look at you when you entered?"
"She didn't seem as if she even saw me, your honour."
"Has she eaten anything, can you tell me?"
"When I fetched her tray last time, sir, I noticed that some
sandwiches and tongue was gone, and there was a little red wine in
the bottom of the tumbler, as though she had drunk some and left a
drop."
"She has ripped up her mattress and is throwing the inside of it
round about her!" Mr Lawrence frowned, pursed his lip, and stared
upon the deck with a strange admixture of gloom and anger.
In truth there had come into his mind the remembrance of a person
who had fallen mad, and amongst the earliest indications of his
insanity was his tendency to tear up everything that would yield to
the power of his fingers, including his clothes.
"By-and-by," said he, "go in and clear the mess up. Take no notice of
her, nor heed her if she speaks. Then fetch the mattress from the
upper bunk in my cabin and place it on her bedstead."
He finished his supper in a very gloomy mood. His character has
been imperfectly drawn if it leaves upon the reader the impression
that he was no more than a gallant, handsome, hectoring scoundrel,
a drunkard, a liar, and a gambler. He was more than this, and better
than this. In him was a very great deal of honest, sturdy, British
human nature, and amongst those who saw the white skin of his
character peeping through the rags and tatters of his morals was the
young lady whom he had locked up in his cabin. Was he driving, had
he driven her mad? This was an awful thought to him, a figure, a
presentment on the canvas of his scheme which his utmost
imagination never could have painted. He was passionately fond of
her. In truth he was risking his neck to win her. His inmost sensibility
as a man and as a gentleman was in perpetual posture of recoil over
the reflection that his hand it was that had made this gently-
nurtured, beautiful, adorable girl a prisoner in a little ship that was
rolling to a port in which she was to be fraudulently sold. He thought
of her in the lovely drawing-room of Old Harbour House: the soft
illumination of wax lights; the sweet incense of flowers; the piano
whose keys were accompanied by her own melodious warblings; her
little dog; all the comforts and luxuries which wealth could provide
her with; all that a tender-hearted and loving father could endow his
only child whom he loved with. And then he thought of her torn
from all this pleasantness and sweetness and elegance, so robed
that in a short period she must become beggarly to the eye; after
her father's hospitable and plentiful table, fed with the poor fare of a
common little ship.
For some time after he had closed his knife and fork he sat at table
shading and supporting his forehead with his hand, his elbow
resting, and deep thought was in his attitude. To one who knew his
story he submitted a picture for memory to cherish. Night was near,
though not yet come, but its shadow was upon the ship, and three
or four stars like little balls of quicksilver ran to and fro athwart the
gleaming black panes of the skylight glass. The hum of a steady
breeze in the stout shrouds, in the cat-harpings, in the drumming
hollow of many sails sounded like the strains of an organ muffled to
the ear by the walls of the church that holds it. The low thunder of
the surge washing past the ship was as constant as its
accompaniment of the concert of creakings, jarrings, shocks in
bulkhead, rudder-post and strong fastenings.
Mr Lawrence started suddenly, stood up, looked round him, and
viewed steadfastly for a space Lucy's cabin door. Then muttering to
himself, "To-morrow—to-morrow!" he made his way towards the
deck.
He had half mounted the cabin ladder when he was brought to a
stand by a sound of voices, of men speaking hard by the
companion-way.
"What beats all my goin' a-fishing," said Mr Thomas Pledge in a
voice which, in spite of its being subdued, and in spite of the noises
of the wind aloft, and of waters washing along the bends yearning
and seething, was distinctly audible to Mr Lawrence as he stood in
the shelter of the companion-way, "is this: this 'ere ship belongs to
Captain Acton. His purchase of her was square and above-board.
Why should he go behind his own back, in a manner of speaking,
and put a man that was an officer in the Royal Navy in charge to
carry her to a port, and sell her by stealth, as though she was a
piece of plunder, and the officer in charge ordered to 'and her over
to a fence, which, John, as of course you know, is the vulgar name
for a man as receives stolen goods? Why is the crew kept in
ignorance of Captain Acton's intention? There's no 'arm in a man a-
selling of his own property. But I says there is a good deal of 'arm in
a man deceiving of sailors for making them an offer to do something
which he don't rightfully explain, and which they'd decline to
undertake if they'd been told the nature of it."
"In all what you say I agree with you, Tom," answered Mr Eagle,
"and I should have thought that Captain Acton was the last man on
this earth to have behaved himself in such a way. For my part I have
always found him so straightforward that the needle ain't truer to
the Pole than he is to his rightful and honourable meaning."
"Ay," said Pledge, "but don't you forget that the needle swings, and
leaves the Polar mark points off."
"But he swings back again," said Mr Eagle, "and is true as God's law
allows him to be in every atom of steel that goes to the making of
him. Have you talked at all forrards about this here matter?"
"Not yet," was the reply.
"Well," said Mr Eagle, "I'm for leaving these 'ere coils on the pin until
the time comes for chucking the fakes down and lettin' go, by which
I mean I'm for waitin' until the Capt'n calls the 'ands aft and reads to
'em the sealed orders he told me about. It'll be time enough to
speak up when we know what Captain Acton's instructions to him
are."
"You may be right," said Pledge, "but I should oncommonly like to
larn what old Jim is a-going to say to this 'ere traverse." Meaning by
old Jim the oldest hand forward, and one who had served Captain
Acton ever since that retired Naval officer had commenced ship-
owning.
At this point Mr Lawrence, who judged that as much had been said
as was likely to interest him, put his foot over the coaming and
passed on to the deck, walking, without heeding the presence of the
two men, to the binnacle stand. He inspected the compass, and then
looked along the deck. Only one figure was now visible, and he had
started to stump the planks in the true deep-sea look-out fashion.
It was, of course, as Mr Lawrence had foreseen. Eagle had betrayed
Mr Lawrence's confidence, and Pledge manifestly was thirsty to carry
the report into the forecastle. As this was a part of Mr Lawrence's
programme his mind made no other comment upon it than that he
was pleased to discover that honest John Eagle, as Captain Acton
held him, was a rogue who could not keep a secret although
imparted by so exalted a personage as the commander of a ship,
and that in breaking his promise the sour, shallow-minded mate was
doing exactly what Mr Lawrence wished.
The night came down in a heavy shadow that was not lightened by
its burden of stars. The foam of the sea looked as spectral as the
faint astral splashes in the velvet deeps on high through which sailed
many visionary shapes of cloud. A little time before it fell dark, and
when the soft, moist crimson of the sun that was set yet lurked in
the west, the steward Paul went aft with lanterns for the cabins
occupied by the Captain, the mate, and Miss Lucy Acton. The great
cabin, or living-room, was already lighted by two lanterns which
swung from hooks on either side the skylight fore-and-aft. The
lanterns Paul bore were small, of iron frames fitted with glass, and in
them was consumed a mesh which was fed with oil.
Mr Lawrence was in the act of passing from the cabin steps to his
berth when Paul, who had received the key from him, came out of
the interior tenanted by Lucy. He looked pale in the lantern light,
ugly, and grotesque, and his face wore an expression as though he
had been terrified.
"Have you hung up the light in Miss Acton's cabin?" said Mr
Lawrence.
"Yes, sir."
"What is she doing?"
"She was lying on the mattress I took in."
"Did she speak?"
"No, sir. At least not at once."
"Has she ripped up the mattress?"
"I didn't see she 'ad, your honour."
"What next?"
"As I turned after 'anging the lantern up I found her stannin' behind
me with a knife in her hand; one of the knives I took in the tray, and
didn't miss when I cleared away. She says to me, speakin' through
her teeth like as though she was tryin' to talk whilst holding on to
something with her mouth, and in the strangest, thinnest voice I
ever heard in all my life, like when you're trying to file down the
head of a nail, 'What do you want here, you loathsome creature?
You come fresh from your forest. Go back before I kill you!' And she
flourished the knife which glittered in her 'and as though it was a-
fire, on which I ran out, sir."
It would have been difficult to tell what was in Mr Lawrence's mind
as he stood viewing Paul for some moments in silence, after that
arched-legged hunchback had ceased. He said in a voice without a
tremor, in tones as steady and collected as those in which he would
ask a man how he was or bid him good-morning: "Have you ever
met with mad people?"
"Yes, sir."
"What proof have they given you that they were mad?"
"A-tearin' up of their clothes and a-goin' about without shame. He
was a man called Micky Cruppin, sir. Another 'ud stop at every pool
to wash his feet. I knowed a man who wouldn't attend sarvice 'cos
he said that the devil always came in, and took a seat beside him.
There was old Mother Compton, who'd spit at a dog if he barked at
her, who used to do her washin' on the Sabbath, sayin' that she was
too good to go to church, and that the parson ought to be 'anged for
having committed a forgery where he last lived. And this she'd say
of a new parson just as she would of t'other who had gone afore
him."
"Do you think Miss Acton mad?" said Mr Lawrence, speaking with an
effort, but determined to have an independent opinion and willing to
believe that the wretch who stood humped, pallid, and terrified
before him might be able to distinguish clearly what was obscured
by his own prejudices, wishes, and dread.
"Yes, sir, I do," was the answer, swiftly delivered, as is the
characteristic of conviction.
Without further speech Mr Lawrence passed into his cabin.
Till midnight he was frequently up and down. The mate in charge
rounding upon his heel would see the figure of the Captain, who
might not have long before gone below, rising and falling against the
stars as he stood grasping a back-stay, watching the darkling ship as
she crushed the phantom lights of the deep out of the black coil of
surge with its trembling lading of stars of the sea-glow, and ever and
anon sending the eye of a man, who has been used to looking out
for ships of the enemy, around the gloom of the horizon. But the
mate of the watch did not know that Mr Lawrence varied this routine
of vigilance by often standing in his own cabin with his ear pressed
to the bulkhead that separated Lucy's berth from his, with the idea
of catching any noises that might be made within.
Shortly after midnight he softly turned the key in Lucy's door and
looked in, and deeming that she lay asleep he passed in, closing the
door behind him, that the roll of the ship might not slam the door
and awaken the sleeper. The light was dim, but sufficiently clear for
eyes that had come out of the gloom or darkness. A mattress lay
upon the deck close against the bedstead, which was emptied of its
furniture, and upon this mattress was stretched the figure of Lucy
Acton. She was fully dressed as in the day, save that she had
removed her jockey-shaped hat. The bolster from the bedstead
supported her head. Some of her dark hair had become disengaged
and lay loosely about her cheek, giving the purity of marble to her
brow in that light, and her sleep was so deep that she lay as though
dead. On the deck close beside her grasp was a common table knife.
Mr Lawrence made a step and quickly picked up the knife and drew
back again, conscious that the fixed gaze will often awake a
slumberer even from deep repose. He stood close to the door
viewing this picture of a sleeping girl in a ship's little cabin irradiated
by a dim light, whose motions, with the rolling and the pitching of
the ship, filled the darkling interior with a hundred dancing spectres.
His marine ear would take no heed of the voices of the ship in that
cabin, the groans and murmurs, the low whistlings and rusty
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like