Вы находитесь на странице: 1из 21

Speaking JavaScript

(Ad, please dont block.) Speaking JavaScript


Homepage
Buy the book

Table of contents

Praise for Speaking JavaScript

Preface
What You Need to Know About This Book

Tips for Reading This Book


The Four Parts of This Book

JavaScript Command Lines

Notational Conventions
Describing syntax

Referring to methods

Command-line interaction

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Tips, notes, and warnings

Quickly Finding Documentation

Safari Books Online

How to Contact Us

Acknowledgments
Preparing for JavaScript

Help with JavaScript

Reviewers

I. JavaScript Quick Start


1. Basic JavaScript
Background
JavaScript Versus ECMAScript

Influences and Nature of the Language

Syntax
An Overview of the Syntax

Statements Versus Expressions

Semicolons

Comments

Variables and Assignment


Assignment

Compound Assignment Operators

Identifiers and Variable Names

Values
Primitive Values Versus Objects

Primitive Values

Objects

undefined and null

Categorizing Values Using typeof and instanceof

Booleans
Truthy and Falsy

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Binary Logical Operators

Equality Operators

Numbers

Operators

Strings
String Operators

String Methods

Statements
Conditionals

Loops

Functions
Function Declarations Are Hoisted

The Special Variable arguments

Too Many or Too Few Arguments

Optional Parameters

Enforcing an Arity

Converting arguments to an Array

Exception Handling

Strict Mode

Variable Scoping and Closures


Variables Are Function-Scoped

Variables Are Hoisted

Closures

The IIFE Pattern: Introducing a New Scope

Objects and Constructors


Single Objects

Arbitrary Property Keys

Extracting Methods

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Functions Inside a Method

Constructors: Factories for Objects

Arrays
Array Literals

Array Methods

Iterating over Arrays

Regular Expressions
Method test(): Is There a Match?

Method exec(): Match and Capture Groups

Method replace(): Search and Replace

Math

Other Functionality of the Standard Library

II. Background
2. Why JavaScript?
Is JavaScript Freely Available?

Is JavaScript Elegant?

Is JavaScript Useful?
Graphical User Interfaces

Other Technologies Complementing JavaScript

Does JavaScript Have Good Tools?

Is JavaScript Fast Enough?

Is JavaScript Widely Used?

Does JavaScript Have a Future?

Conclusion

3. The Nature of JavaScript


Quirks and Unorthodox Features

Elegant Parts

Influences

4. How JavaScript Was Created

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

5. Standardization: ECMAScript

6. Historical JavaScript Milestones

III. JavaScript in Depth


7. JavaScripts Syntax
An Overview of the Syntax

Comments

Expressions Versus Statements


Expressions

Statements

Control Flow Statements and Blocks

Rules for Using Semicolons


No Semicolon After a Statement Ending with a Block

The Empty Statement

Automatic Semicolon Insertion

Legal Identifiers

Invoking Methods on Number Literals

Strict Mode
Switching on Strict Mode

Strict Mode: Recommended, with Caveats

Variables Must Be Declared in Strict Mode

Functions in Strict Mode

Setting and Deleting Immutable Properties Fails with an Exception in


Strict Mode

Unqualified Identifiers Cant Be Deleted in Strict Mode

eval() Is Cleaner in Strict Mode

Features That Are Forbidden in Strict Mode

8. Values
JavaScripts Type System
JavaScripts Types

Static Versus Dynamic

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Static Typing Versus Dynamic Typing

Static Type Checking Versus Dynamic Type Checking

Coercion

Primitive Values Versus Objects

Primitive Values

Objects

undefined and null


Occurrences of undefined and null

Checking for undefined or null

The History of undefined and null

Changing undefined

Wrapper Objects for Primitives


Wrapper Objects Are Different from Primitives

Wrapping and Unwrapping Primitives

Primitives Borrow Their Methods from Wrappers

Type Coercion
Type Coercion Can Hide Bugs

Functions for Converting to Boolean, Number, String, and Object

Algorithm: ToPrimitive()Converting a Value to a Primitive

9. Operators
Operators and Objects

Assignment Operators
Compound Assignment Operators

Equality Operators: === Versus ==


Strict Equality (===, !==)

Normal (Lenient) Equality (==, !=)

There Are No Valid Use Cases for ==

Ordering Operators
The Algorithm

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

The Plus Operator (+)


The Algorithm

Operators for Booleans and Numbers

Special Operators
The Conditional Operator ( ? : )

The Comma Operator

The void Operator

Categorizing Values via typeof and instanceof


typeof: Categorizing Primitives

instanceof: Checking Whether an Object Is an Instance of a Given


Constructor

Object Operators

10. Booleans
Converting to Boolean
Manually Converting to Boolean

Truthy and Falsy Values

Logical Operators
Binary Logical Operators: And (&&) and Or (||)

Logical And (&&)

Logical Or (||)

Logical Not (!)

Equality Operators, Ordering Operators

The Function Boolean

11. Numbers
Number Literals
Exponent

Invoking Methods on Literals

Converting to Number
Manually Converting to Number

parseFloat()

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Special Number Values


NaN

Infinity

Two Zeros

The Internal Representation of Numbers


Special Exponents

Handling Rounding Errors

Integers in JavaScript
Ranges of Integers

Representing Integers as Floating-Point Numbers

Safe Integers

Converting to Integer
Integers via Math.floor(), Math.ceil(), and Math.round()

Integers via the Custom Function ToInteger()

32-bit Integers via Bitwise Operators

Integers via parseInt()

Arithmetic Operators

Bitwise Operators
Background Knowledge

Bitwise Not Operator

Binary Bitwise Operators

Bitwise Shift Operators

The Function Number

Number Constructor Properties

Number Prototype Methods


Number.prototype.toFixed(fractionDigits?)

Number.prototype.toPrecision(precision?)

Number.prototype.toString(radix?)

Number.prototype.toExponential(fractionDigits?)

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Functions for Numbers

Sources for This Chapter

12. Strings
String Literals

Escaping in String Literals

Character Access

Converting to String
Manually Converting to String

Comparing Strings

Concatenating Strings
Concatenation: The Plus (+) Operator

Concatenation: Joining an Array of String Fragments

The Function String

String Constructor Method

String Instance Property length

String Prototype Methods


Extract Substrings

Transform

Search and Compare

Test, Match, and Replace with Regular Expressions

13. Statements
Declaring and Assigning Variables

The Bodies of Loops and Conditionals

Loops
Mechanisms to Be Used with Loops

while

do-while

for

for-in

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

for each-in

Conditionals
if-then-else

switch

The with Statement


Syntax and Semantics

The with Statement Is Deprecated

The Rationale for the Deprecation

The debugger Statement

14. Exception Handling


What Is Exception Handling?

Exception Handling in JavaScript


throw

try-catch-finally

Examples

Error Constructors

Stack Traces

Implementing Your Own Error Constructor

15. Functions
The Three Roles of Functions in JavaScript

Terminology: Parameter Versus Argument

Defining Functions
Function Expressions

Function Declarations

The Function Constructor

Hoisting

The Name of a Function

Which Is Better: A Function Declaration or a Function Expression?

More Control over Function Calls: call(), apply(), and bind()

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

func.apply(thisValue, argArray)

func.bind(thisValue, arg1, ..., argN)

Handling Missing or Extra Parameters


All Parameters by Index: The Special Variable arguments

Mandatory Parameters, Enforcing a Minimum Arity

Optional Parameters

Simulating Pass-by-Reference Parameters

Pitfall: Unexpected Optional Parameters

Named Parameters
Named Parameters as Descriptions

Optional Named Parameters

Simulating Named Parameters in JavaScript

16. Variables: Scopes, Environments, and Closures


Declaring a Variable

Background: Static Versus Dynamic

Background: The Scope of a Variable

Variables Are Function-Scoped

Variable Declarations Are Hoisted

Introducing a New Scope via an IIFE


IIFE Variation: Prefix Operators

IIFE Variation: Already Inside Expression Context

IIFE Variation: An IIFE with Parameters

IIFE Applications

Global Variables
Best Practice: Avoid Creating Global Variables

Module Systems Lead to Fewer Globals

The Global Object


Cross-Platform Considerations

Use Cases for window

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Environments: Managing Variables

Closures: Functions Stay Connected to Their Birth Scopes


Handling Closures via Environments

Pitfall: Inadvertently Sharing an Environment

17. Objects and Inheritance


Layer 1: Single Objects
Kinds of Properties

Object Literals

Dot Operator (.): Accessing Properties via Fixed Keys

Unusual Property Keys

Bracket Operator ([]): Accessing Properties via Computed Keys

Converting Any Value to an Object

this as an Implicit Parameter of Functions and Methods


Calling Functions While Setting this: call(), apply(), and bind()

apply() for Constructors

Pitfall: Losing this When Extracting a Method

Pitfall: Functions Inside Methods Shadow this

Layer 2: The Prototype Relationship Between Objects


Inheritance

Overriding

Sharing Data Between Objects via a Prototype

Getting and Setting the Prototype

The Special Property __proto__

Setting and Deleting Affects Only Own Properties

Iteration and Detection of Properties


Listing Own Property Keys

Listing All Property Keys

Checking Whether a Property Exists

Examples

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Best Practices: Iterating over Own Properties

Accessors (Getters and Setters)


Defining Accessors via an Object Literal

Defining Accessors via Property Descriptors

Accessors and Inheritance

Property Attributes and Property Descriptors


Property Attributes

Property Descriptors

Getting and Defining Properties via Descriptors

Copying an Object

Properties: Definition Versus Assignment

Inherited Read-Only Properties Cant Be Assigned To

Enumerability: Best Practices

Protecting Objects
Preventing Extensions

Sealing

Freezing

Pitfall: Protection Is Shallow

Layer 3: ConstructorsFactories for Instances


The new Operator Implemented in JavaScript

Terminology: The Two Prototypes

The constructor Property of Instances

The instanceof Operator

Tips for Implementing Constructors

Data in Prototype Properties


Avoid Prototype Properties with Initial Values for Instance Properties

Avoid Nonpolymorphic Prototype Properties

Polymorphic Prototype Properties

Keeping Data Private

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Private Data in the Environment of a Constructor (Crockford Privacy


Pattern)

Private Data in Properties with Marked Keys

Private Data in Properties with Reified Keys

Keeping Global Data Private via IIFEs

Layer 4: Inheritance Between Constructors


Inheriting Instance Properties

Inheriting Prototype Properties

Ensuring That instanceof Works

Overriding a Method

Making a Supercall

Avoiding Hardcoding the Name of the Superconstructor

Example: Constructor Inheritance in Use

Example: The Inheritance Hierarchy of Built-in Constructors

Antipattern: The Prototype Is an Instance of the Superconstructor

Methods of All Objects


Conversion to Primitive

Object.prototype.toLocaleString()

Prototypal Inheritance and Properties

Generic Methods: Borrowing Methods from Prototypes


Accessing Object.prototype and Array.prototype via Literals

Examples of Calling Methods Generically

Array-Like Objects and Generic Methods

A List of All Generic Methods

Pitfalls: Using an Object as a Map


Pitfall 1: Inheritance Affects Reading Properties

Pitfall 2: Overriding Affects Invoking Methods

Pitfall 3: The Special Property __proto__

The dict Pattern: Objects Without Prototypes Are Better Maps

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Best Practices

Cheat Sheet: Working with Objects

18. Arrays
Overview
Arrays Are Maps, Not Tuples

Arrays Can Also Have Properties

Creating Arrays
The Array Constructor

Multidimensional Arrays

Array Indices
The in Operator and Indices

Deleting Array Elements

Array Indices in Detail

length
Manually Increasing the Length of an Array

Decreasing the Length of an Array

The Maximum Length

Holes in Arrays
Creating Holes

Sparse Arrays Versus Dense Arrays

Which Operations Ignore Holes, and Which Consider Them?

Removing Holes from Arrays

Array Constructor Method

Array Prototype Methods

Adding and Removing Elements (Destructive)

Sorting and Reversing Elements (Destructive)


Comparing Numbers

Comparing Strings

Comparing Objects

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Concatenating, Slicing, Joining (Nondestructive)

Searching for Values (Nondestructive)

Iteration (Nondestructive)
Examination Methods

Transformation Methods

Reduction Methods

Pitfall: Array-Like Objects

Best Practices: Iterating over Arrays

19. Regular Expressions


Regular Expression Syntax
Atoms: General

Atoms: Character Classes

Atoms: Groups

Quantifiers

Assertions

Disjunction

Unicode and Regular Expressions

Creating a Regular Expression


Literal Versus Constructor

Flags

Instance Properties of Regular Expressions

Examples of Creating Regular Expressions

RegExp.prototype.test: Is There a Match?

String.prototype.search: At What Index Is There a Match?

RegExp.prototype.exec: Capture Groups


First Match (Flag /g Not Set)

All Matches (Flag /g Set)

String.prototype.match: Capture Groups or Return All Matching Substrings

String.prototype.replace: Search and Replace

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Replacement Is a String

Replacement Is a Function

Problems with the Flag /g

Tips and Tricks


Quoting Text

Pitfall: Without an Assertion (e.g., ^, $), a Regular Expression Is Found


Anywhere

Matching Everything or Nothing

Manually Implementing Lookbehind

Regular Expression Cheat Sheet

20. Dates
The Date Constructor

Date Constructor Methods

Date Prototype Methods


Time Unit Getters and Setters

Various Getters and Setters

Convert a Date to a String

Date Time Formats


Date Formats (No Time)

Time Formats (No Date)

Date Time Formats

Time Values: Dates as Milliseconds Since 1970-01-01


Converting a Date to a Number

21. Math
Math Properties

Numerical Functions

Trigonometric Functions

Other Functions

22. JSON
Background

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Data Format

History

Grammar

JSON.stringify(value, replacer?, space?)


Data Ignored by JSON.stringify()

The toJSON() Method

JSON.parse(text, reviver?)

Transforming Data via Node Visitors


JSON.stringify()

JSON.parse()

23. Standard Global Variables


Constructors

Error Constructors

Nonconstructor Functions
Encoding and Decoding Text

Categorizing and Parsing Numbers

Dynamically Evaluating JavaScript Code via eval() and new Function()


Evaluating Code Using eval()

Evaluating Code Using new Function()

eval() Versus new Function()

Best Practices

Conclusion

The Console API


How Standardized Is the Console API Across Engines?

Simple Logging

Checking and Counting

Formatted Logging

Profiling and Timing

Namespaces and Special Values

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

24. Unicode and JavaScript


Unicode History

Important Unicode Concepts

Code Points

Unicode Encodings

JavaScript Source Code and Unicode


Source Code Internally

Source Code Externally

JavaScript Strings and Unicode


Escape Sequences

Refering to Astral Plane Characters via Escapes

Counting Characters

Unicode Normalization

JavaScript Regular Expressions and Unicode


Matching Any Code Unit and Any Code Point

Libraries

Recommended Reading and Chapter Sources

25. New in ECMAScript5


New Features

Syntactic Changes

New Functionality in the Standard Library


Metaprogramming

New Methods

JSON

Tips for Working with Legacy Browsers

IV. Tips, Tools, and Libraries


26. A Meta Code Style Guide
Existing Style Guides

General Tips
Code Should Be Consistent

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Code Should Be Easy to Understand

Commonly Accepted Best Practices


Brace Styles

Prefer Literals to Constructors

Dont Be Clever

Acceptable Cleverness

Controversial Rules
Syntax

Variables

Object Orientation

Miscellaneous

Conclusion

27. Language Mechanisms for Debugging

28. Subclassing Built-ins


Terminology

Obstacle 1: Instances with Internal Properties


Workaround for Obstacle 1

Caveats

Obstacle 2: A Constructor That Cant Be Called as a Function


Workaround for Obstacle 2

Another Solution: Delegation

29. JSDoc: Generating API Documentation


The Basics of JSDoc
Syntax

Naming Types

Basic Tags

Documenting Functions and Methods

Inline Type Information (Inline Doc Comments)

Documenting Variables, Parameters, and Instance Properties

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]


Speaking JavaScript

Documenting Classes
Defining a Class via a Constructor Function

Defining a Class via an Object Literal

Defining a Class via an Object Literal with an @constructs Method

Subclassing

Other Useful Tags

30. Libraries
Shims Versus Polyfills

Four Language Libraries

The ECMAScript Internationalization API


The ECMAScript Internationalization API, Edition 1

What Kind of Standard Is It?

When Can I Use It?

Further Reading

Directories for JavaScript Resources

31. Module Systems and Package Managers


Module Systems

Package Managers

Quick and Dirty Modules

32. More Tools

33. What to Do Next

Index

About the Author

Colophon

Copyright

http://speakingjs.com/es5/[8/21/2016 1:07:52 AM]

Вам также может понравиться