Docsity

Eloquent javascript (1), Guide, Progetti e Ricerche di Progettazione e analisi di algoritmi

Anteprima parziale del testo

Scarica Eloquent javascript (1) e più Guide, Progetti e Ricerche in PDF di Progettazione e analisi di algoritmi solo su Docsity!

Eloquent JavaScript

A Modern Introduction to Programming

Marijn Haverbeke

Copyright © 2014 by Marijn Haverbeke

This work is licensed under a Creative Commons attribution-noncommercial license (http://creativecommons.org/licenses/by-nc/3.0/). All code in the book may also be considered licensed under an MIT license (http:// opensource.org/licenses/MIT). The illustrations are contributed by various artists: Cover by Wasif Hyder. Computer (introduction) and unicycle people (Chapter 21) by Max Xiantu. Sea of bits (Chapter 1) and weresquirrel (Chapter 4) by Margarita Martínez and José Menor. Octopuses (Chapter 2 and 4) by Jim Tierney. Object with on/off switch (Chapter 6) by Dyle MacGregor. Regular expression diagrams in Chapter 9 generated with regexper.com by Jeff Avallone. Game concept for Chapter 15 by Thomas Palef. Pixel art in Chapter 16 by Antonio Perdomo Pastor. The second edition of Eloquent JavaScript was made possible by 454 financial backers.

You can buy a print version of this book, with an extra bonus chapter included, printed by No Starch Press at http://www.amazon.com/gp/product/ 1593275846/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN= 1593275846&linkCode=as2&tag=marijhaver-20&linkId=VPXXXSRYC5COG5R5.

i

  • On programming
  • Why language matters
  • What is JavaScript?
  • Code, and what to do with it
  • Overview of this book
  • Typographic conventions
  • 1 Values, Types, and Operators
    • Values
    • Numbers
    • Strings
    • Unary operators
    • Boolean values
    • Undefined values
    • Automatic type conversion
    • Summary
  • 2 Program Structure
    • Expressions and statements
    • Variables
    • Keywords and reserved words
    • The environment
    • Functions
    • The console.log function
    • Return values
    • prompt and confirm
    • Control flow
    • Conditional execution
    • while and do loops
    • Indenting Code
    • for loops
    • Breaking Out of a Loop
    • Updating variables succinctly
    • Dispatching on a value with switch
    • Capitalization
    • Comments
    • Summary
    • Exercises
  • 3 Functions
    • Defining a function
    • Parameters and scopes
    • Nested scope
    • Functions as values
    • Declaration notation
    • The call stack
    • Optional Arguments
    • Closure
    • Recursion
    • Growing functions
    • Functions and side effects
    • Summary
    • Exercises
  • 4 Data Structures: Objects and Arrays
    • The weresquirrel
    • Data sets
    • Properties
    • Methods
    • Objects
    • Mutability
    • The lycanthrope’s log
    • Computing correlation
    • Objects as maps
    • The final analysis
    • Further arrayology
    • Strings and their properties
    • The arguments object
    • The Math object
    • The global object
    • Summary
    • Exercises
  • 5 Higher-Order Functions
    • Abstraction
    • Abstracting array traversal
    • Higher-order functions
    • Passing along arguments
    • JSON
    • Filtering an array
    • Transforming with map
    • Summarizing with reduce
    • Composability
    • The cost
    • Great-great-great-great-…
    • Binding
    • Summary
    • Exercises
  • 6 The Secret Life of Objects
    • History
    • Methods
    • Prototypes
    • Constructors
    • Overriding derived properties
    • Prototype interference
    • Prototype-less objects
    • Polymorphism
    • Laying out a table
    • Getters and setters
    • Inheritance
    • The instanceof operator
    • Summary
    • Exercises
  • 7 Project: Electronic Life
    • Definition
    • Representing space
    • A critter’s programming interface
    • The world object
    • this and its scope
    • Animating life
    • It moves
    • More life forms
    • A more lifelike simulation
    • Action handlers
    • Populating the new world
    • Bringing it to life
    • Exercises
  • 8 Bugs and Error Handling
    • Programmer mistakes
    • Strict mode
    • Testing
    • Debugging
    • Error propagation
    • Exceptions
    • Cleaning up after exceptions
    • Selective catching
    • Assertions
    • Summary
    • Exercises
  • 9 Regular Expressions
    • Creating a regular expression
    • Testing for matches
    • Matching a set of characters
    • Repeating parts of a pattern
    • Grouping subexpressions
    • Matches and groups
    • The date type
    • Word and string boundaries
    • Choice patterns
    • The mechanics of matching
    • Backtracking
    • The replace method
    • Greed
    • Dynamically creating RegExp objects
    • The search method
    • The lastIndex property
    • Parsing an INI file
    • International characters
    • Summary
    • Exercises
  • 10 Modules
    • Why modules help
    • Using functions as namespaces
    • Objects as interfaces
    • Detaching from the global scope
    • Evaluating data as code
    • Require
    • Slow-loading modules
    • Interface design
    • Summary
    • Exercises
  • 11 Project: A Programming Language
    • Parsing
    • The evaluator
    • Special forms
    • The environment
    • Functions
    • Compilation
    • Cheating
    • Exercises
  • 12 JavaScript and the Browser
    • Networks and the Internet
    • The Web
    • HTML
    • HTML and JavaScript
    • In the sandbox
    • Compatibility and the browser wars
  • 13 The Document Object Model
    • Document structure
    • Trees
    • The standard
    • Moving through the tree
    • Finding elements
    • Changing the document
    • Creating nodes
    • Attributes
    • Layout
    • Styling
    • Cascading styles
    • Query selectors
    • Positioning and animating
    • Summary
    • Exercises
  • 14 Handling Events
    • Event handlers
    • Events and DOM nodes
    • Event objects
    • Propagation
    • Default actions
    • Key events
    • Mouse clicks
    • Mouse motion
    • Scroll events
    • Focus events
    • Load event
    • Script execution timeline
    • Setting timers
    • Debouncing
    • Summary
    • Exercises
  • 15 Project: A Platform Game
    • The game
    • The technology
    • Levels
    • Reading a level
    • Actors
    • Encapsulation as a burden
    • Drawing
    • Motion and collision
    • Actors and actions
    • Tracking keys
    • Running the game
    • Exercises
  • 16 Drawing on Canvas
    • SVG
    • The canvas element
    • Filling and stroking
    • Paths
    • Curves
    • Drawing a pie chart
    • Text
    • Images
    • Transformation
    • Storing and clearing transformations
    • Back to the game
    • Choosing a graphics interface
    • Summary
    • Exercises
  • 17 HTTP
    • The protocol
    • Browsers and HTTP
    • XMLHttpRequest
    • Sending a request
    • Asynchronous Requests
    • Fetching XML Data
    • HTTP sandboxing
    • Abstracting requests
    • Promises
    • Appreciating HTTP
    • Security and HTTPS
    • Summary
    • Exercises
  • 18 Forms and Form Fields
    • Fields
    • Focus
    • Disabled fields
    • The form as a whole
    • Text fields
    • Checkboxes and radio buttons
    • Select fields
    • File fields
    • Storing data client-side
    • Summary
    • Exercises
  • 19 Project: A Paint Program
    • Implementation
    • Building the DOM
    • The foundation
    • Tool selection
    • Color and brush size
    • Saving
    • Loading image files
    • Finishing up
    • Exercises
  • 20 Node.js
    • Background
    • Asynchronicity
    • The node command
    • Modules
    • Installing with NPM
    • The file system module
    • The HTTP module
    • Streams
    • A simple file server
    • Error handling
    • Summary
    • Exercises
  • 21 Project: Skill-Sharing Website
    • Design
    • Long polling
    • HTTP interface
    • The server
    • The client
    • Exercises
    • Program Structure
    • Functions
    • Data Structures: Objects and Arrays
    • Higher-Order Functions
    • The Secret Life of Objects
    • Project: Electronic Life
    • Bugs and Error Handling
    • Regular Expressions
    • Modules
    • Project: A Programming Language
    • The Document Object Model
    • Handling Events
    • Project: A Platform Game
    • Drawing on Canvas
    • HTTP
    • Forms and Form Fields
    • Project: A Paint Program

Introduction

This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things.

We’ve found two effective ways of bridging the communication gap be- tween us, squishy biological organisms with a talent for social and spatial reasoning, and computers, unfeeling manipulators of meaningless data. The first is to appeal to our sense of the physical world and build in- terfaces that mimic that world and allow us to manipulate shapes on a screen with our fingers. This works very well for casual machine inter- action. But we have not yet found a good way to use the point-and-click ap- proach to communicate things to the computer that the designer of the interface did not anticipate. For open-ended interfaces, such as instruct- ing the computer to perform arbitrary tasks, we’ve had more luck with an approach that makes use of our talent for language: teaching the machine a language. Human languages allow words and phrases to be combined in many ways, which allows us to say many different things. Computer languages, though typically less grammatically flexible, follow a similar principle.

Casual computing has become much more widespread in the past 20 years, and language-based interfaces, which once were the default way in which people interacted with computers, have largely been replaced with graphical interfaces. But they are still there, if you know where to look. One such language, JavaScript, is built into almost every web browser and is thus available on just about every consumer device. This book intends to make you familiar enough with this language to be able to make a computer do what you want.

On programming

I do not enlighten those who are not eager to learn, nor arouse those who are not anxious to give an explanation themselves. If I have presented one corner of the square and they cannot come back to me with the other three, I should not go over the points again. —Confucius

Besides explaining JavaScript, I also will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are typically simple and clear. But programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You’re building your own maze, in a way, and you might just get lost in it. There will be times when reading this book feels terribly frustrating. If you are new to programming, there will be a lot of new material to digest. Much of this material will then be combined in ways that require you to make additional connections. It is up to you to make the necessary effort. When you are struggling to follow the book, do not jump to any conclusions about your own capabilities. You are fine—you just need to keep at it. Take a break, reread some material, and always make sure you read and understand the example programs and exercises. Learning is hard work, but everything you learn is yours and will make subsequent learning easier.

The computer programmer is a creator of universes for which he [sic] alone is responsible. Universes of virtually unlimited

will always be new challenges and new territory to explore. Program- mers who refuse to keep exploring will stagnate, forget their joy, and get bored with their craft.

Why language matters

In the beginning, at the birth of computing, there were no programming languages. Programs looked something like this:

00110001 00000000 00000000 00110001 00000001 00000001 00110011 00000001 00000010 01010001 00001011 00000010 00100010 00000010 00001000 01000011 00000001 00000000 01000001 00000001 00000001 00010000 00000010 00000000 01100010 00000000 00000000

That is a program to add the numbers from 1 to 10 together and print out the result: 1 + 2 + ... + 10 = 55. It could run on a simple, hypo- thetical machine. To program early computers, it was necessary to set large arrays of switches in the right position or punch holes in strips of cardboard and feed them to the computer. You can probably imagine how tedious and error-prone this procedure was. Even writing simple programs required much cleverness and discipline. Complex ones were nearly inconceivable. Of course, manually entering these arcane patterns of bits (the ones and zeros) did give the programmer a profound sense of being a mighty wizard. And that has to be worth something in terms of job satisfaction. Each line of the previous program contains a single instruction. It could be written in English like this:

  1. Store the number 0 in memory location 0.
  2. Store the number 1 in memory location 1.
  3. Store the value of memory location 1 in memory location 2.
  4. Subtract the number 11 from the value in memory location 2.
  5. If the value in memory location 2 is the number 0, continue with instruction 9.
  1. Add the value of memory location 1 to memory location 0.
  2. Add the number 1 to the value of memory location 1.
  3. Continue with instruction 3.
  4. Output the value of memory location 0.

Although that is already more readable than the soup of bits, it is still rather unpleasant. It might help to use names instead of numbers for the instructions and memory locations.

Set " total " to 0. Set " count " to 1. [ loop ] Set " compare " to " count ". Subtract 11 from " compare ". If " compare " is zero , continue at [ end ]. Add " count " to " total ". Add 1 to " count ". Continue at [ loop ]. [ end ] Output " total ".

Can you see how the program works at this point? The first two lines give two memory locations their starting values: total will be used to build up the result of the computation, and count will keep track of the number that we are currently looking at. The lines using compare are probably the weirdest ones. The program wants to see whether count is equal to 11 in order to decide whether it can stop running. Because our hypothetical machine is rather primitive, it can only test whether a number is zero and make a decision (or jump) based on that. So it uses the memory location labeled compare to compute the value of count

  • 11 and makes a decision based on that value. The next two lines add the value of count to the result and increment count by 1 every time the program has decided that count is not 11 yet. Here is the same program in JavaScript: var total = 0, count = 1; while ( count <= 10) { total += count ; count += 1; } console. log ( total );

applications possible—applications with which you can interact directly, without doing a page reload for every action. But it is also used in more traditional websites to provide various forms of interactivity and cleverness. It is important to note that JavaScript has almost nothing to do with the programming language named Java. The similar name was in- spired by marketing considerations, rather than good judgment. When JavaScript was being introduced, the Java language was being heavily marketed and was gaining popularity. Someone thought it was a good idea to try to ride along on this success. Now we are stuck with the name. After its adoption outside of Netscape, a standard document was writ- ten to describe the way the JavaScript language should work to make sure the various pieces of software that claimed to support JavaScript were actually talking about the same language. This is called the EC- MAScript standard, after the Ecma International organization that did the standardization. In practice, the terms ECMAScript and JavaScript can be used interchangeably—they are two names for the same language. There are those who will say terrible things about the JavaScript lan- guage. Many of these things are true. When I was required to write something in JavaScript for the first time, I quickly came to despise it. It would accept almost anything I typed but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, of course, but there is a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder because the system will not point them out to you. This flexibility also has its advantages, though. It leaves space for a lot of techniques that are impossible in more rigid languages, and as you will see (for example in Chapter 10) it can be used to overcome some of JavaScript’s shortcomings. After learning the language properly and working with it for a while, I have learned to actually like JavaScript. There have been several versions of JavaScript. ECMAScript version 3 was the widely supported version in the time of JavaScript’s ascent to dominance, roughly between 2000 and 2010. During this time, work

was underway on an ambitious version 4, which planned a number of radical improvements and extensions to the language. Changing a living, widely used language in such a radical way turned out to be politically difficult, and work on the version 4 was abandoned in 2008, leading to the much less ambitious version 5 coming out in 2009. We’re now at the point where all major browsers support version 5, which is the language version that this book will be focusing on. A version 6 is in the process of being finalized, and some browsers are starting to support new features from this version. Web browsers are not the only platforms on which JavaScript is used. Some databases, such as MongoDB and CouchDB, use JavaScript as their scripting and query language. Several platforms for desktop and server programming, most notably the Node.js project (the subject of Chapter 20) are providing a powerful environment for programming JavaScript outside of the browser.

Code, and what to do with it

Code is the text that makes up programs. Most chapters in this book contain quite a lot of it. In my experience, reading code and writing code are indispensable parts of learning to program, so try to not just glance over the examples. Read them attentively and understand them. This may be slow and confusing at first, but I promise that you will quickly get the hang of it. The same goes for the exercises. Don’t assume you understand them until you’ve actually written a working solution. I recommend you try your solutions to exercises in an actual JavaScript interpreter. That way, you’ll get immediate feedback on whether what you are doing is working, and, I hope, you’ll be tempted to experiment and go beyond the exercises. The easiest way to run the example code in the book, and to ex- periment with it, is to look it up in the online version of the book at eloquentjavascript.net. There, you can click any code example to edit and run it and to see the output it produces. To work on the exercises, go to eloquentjavascript.net/code , which provides starting code for each coding exercise and allows you to look at the solutions. If you want to run the programs defined in this book outside of the