JavaScript_ The Good Parts

This is not a book for dummies. This book is small, but it is dense. There is a lot of Material packed into it.


Douglas Crockford


172 Pages

19578 Reads

59 Downloads

English

PDF Format

1.48 MB

Java Script

Download PDF format


  • Douglas Crockford   
  • 172 Pages   
  • 18 May 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    JavaScript: The Good Parts read more..

  • Page - 4

    Other resources from O’Reilly Related titles High Performance Web Sites JavaScript and DHTML Cookbook ™ JavaScript: The Definitive Guide Learning JavaScript oreilly.com oreilly.com is more than a complete catalog of O’Reilly books. You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples. oreillynet.com is the essential portal for developers interested in read more..

  • Page - 5

    JavaScript: The Good Parts Douglas Crockford Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo read more..

  • Page - 6

    JavaScript: The Good Parts by Douglas Crockford Copyright © 2008 Yahoo! Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles read more..

  • Page - 7

    For the Lads: Clement, Philbert, Seymore, Stern, and, lest we forget, C. Twildo. read more..

  • Page - 8

    read more..

  • Page - 9

    vii Table of Contents actionGoTo:13,Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi actionGoTo:17,1. actionGoTo:17,Good Parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 10

    viii | Table of Contents actionGoTo:42,4. actionGoTo:42,Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 actionGoTo:42,Function Objects actionGoTo:42, 26 actionGoTo:43,Function Literal actionGoTo:43, 27 actionGoTo:43,Invocation actionGoTo:43, 27 actionGoTo:47,Arguments actionGoTo:47, 31 read more..

  • Page - 11

    Table of Contents | ix actionGoTo:94,8. actionGoTo:94,Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 actionGoTo:110,9. actionGoTo:110,Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 12

    read more..

  • Page - 13

    xi Preface 1 If we offend, it is with our good will That you should think, we come not to offend, But with good will. To show our simple skill, That is the true beginning of our end. —William Shakespeare, A Midsummer Night’s Dream This is a book about the JavaScript programming language. It is intended for pro- grammers who, by happenstance or curiosity, are venturing read more..

  • Page - 14

    xii | Preface Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, filenames, and file extensions. Constant width Indicates computer coding in a broad sense. This includes commands, options, variables, attributes, keys, requests, functions, methods, types, classes, modules, properties, parameters, values, objects, events, event read more..

  • Page - 15

    Preface | xiii How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any addi- tional information. You read more..

  • Page - 16

    read more..

  • Page - 17

    1 Chapter 1 CHAPTER 1 Good Parts 1 …setting the attractions of my good parts aside I have no other charms. —William Shakespeare, The Merry Wives of Windsor When I was a young journeyman programmer, I would learn about every feature of the languages I was using, and I would attempt to use all of those features when I wrote. I suppose it was a way of showing off, and read more..

  • Page - 18

    2 | Chapter 1: Good Parts Fortunately, JavaScript has some extraordinarily good parts. In JavaScript, there is a beautiful, elegant, highly expressive language that is buried under a steaming pile of good intentions and blunders. The best nature of JavaScript is so effectively hidden that for many years the prevailing opinion of JavaScript was that it was an unsightly, incompetent read more..

  • Page - 19

    Analyzing JavaScript | 3 Analyzing JavaScript JavaScript is built on some very good ideas and a few very bad ones. The very good ideas include functions, loose typing, dynamic objects, and an expres- sive object literal notation. The bad ideas include a programming model based on global variables. JavaScript’s functions are first class objects with (mostly) lexical scoping. JavaScript read more..

  • Page - 20

    4 | Chapter 1: Good Parts The standard that defines JavaScript (aka JScript) is the third edition of The ECMAScript Programming Language, which is available from actionURI(http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf):http://www.ecma- actionURI(http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf):international.org/publications/files/ecma-st/ECMA-262.pdf. The language described in this read more..

  • Page - 21

    5 Chapter 2 CHAPTER 2 Grammar 2 I know it well: I read it in the grammar long ago. —William Shakespeare, The Tragedy of Titus Andronicus This chapter introduces the grammar of the good parts of JavaScript, presenting a quick overview of how the language is structured. We will represent the grammar with railroad diagrams. The rules for interpreting these diagrams are simple: • read more..

  • Page - 22

    6 | Chapter 2: Grammar JavaScript offers two forms of comments, block comments formed with /* */ and line-ending comments starting with // . Comments should be used liberally to improve the readability of your programs. Take care that the comments always accu- rately describe the code. Obsolete comments are worse than no comments. The /* */ form of block comments came from a read more..

  • Page - 23

    Numbers | 7 else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var volatile void while with Most of the reserved words in this list are not used in the language. The list does read more..

  • Page - 24

    8 | Chapter 2: Grammar If a number literal has an exponent part, then the value of the literal is computed by multiplying the part before the e by 10 raised to the power of the part after the e .So 100 and 1e2 are the same number. Negative numbers can be formed by using the – prefix operator. The value NaN is a number value that is the result of an read more..

  • Page - 25

    Strings | 9 The escape sequences allow for inserting characters into strings that are not nor- mally permitted, such as backslashes, quotes, and control characters. The \u conven- tion allows for specifying character code points numerically. "A" === "\u0041" Strings have a length property. For example, "seven".length is 5. Strings are immutable. Once it is made, a read more..

  • Page - 26

    10 | Chapter 2: Grammar Two strings containing exactly the same characters in the same order are considered to be the same string. So: 'c' + 'a' + 't' === 'cat' is true. Strings have methods (see actionGoTo:94,Chapter actionGoTo:94,8): 'cat'.toUpperCase( ) === 'CAT' Statements A compilation unit contains a set of executable statements. In web browsers, each <script> tag delivers a read more..

  • Page - 27

    Statements | 11 Here are the falsy values: • false • null statements expression statement ; do statement for statement while statement switch statement if statement try statement disruptive statement name label : disruptive statement break statement return statement throw statement block {} statements if statement if ) expression ( block then block else read more..

  • Page - 28

    12 | Chapter 2: Grammar • undefined • The empty string '' • The number 0 • The number NaN All other values are truthy, including true , the string 'false' , and all objects. The switch statement performs a multiway branch. It compares the expression for equality with all of the specified cases. The expression can produce a number or a string. When an exact match is read more..

  • Page - 29

    Statements | 13 The other form (called for in ) enumerates the property names (or keys) of an object. On each iteration, another property name string from the object is assigned to the variable. It is usually necessary to test object.hasOwnProperty(variable) to determine whether the property name is truly a member of the object or was found instead on the proto- type chain. for read more..

  • Page - 30

    14 | Chapter 2: Grammar The throw statement raises an exception. If the throw statement is in a try block, then control goes to the catch clause. Otherwise, the function invocation is abandoned, and control goes to the catch clause of the try in the calling function. The expression is usually an object literal containing a name property and a message property. The catcher of read more..

  • Page - 31

    Expressions | 15 An expression statement can either assign values to one or more variables or mem- bers, invoke a method, delete a property from an object. The = operator is used for assignment. Do not confuse it with the === equality operator. The += operator can add or concatenate. Expressions The simplest expressions are a literal value (such as a string or number), a read more..

  • Page - 32

    16 | Chapter 2: Grammar The operators at the top of the operator precedence list in actionGoTo:32,Table actionGoTo:32,2-1 have higher pre- cedence. They bind the tightest. The operators at the bottom have the lowest prece- dence. Parentheses can be used to alter the normal precedence, so: 2 + 3 * 5 === 17 (2 + 3) * 5 === 25 The values produced by typeof are 'number' , read more..

  • Page - 33

    Literals | 17 The || operator produces the value of its first operand if the first operand is truthy. Otherwise, it produces the value of the second operand. Invocation causes the execution of a function value. The invocation operator is a pair of parentheses that follow the function value. The parentheses can contain argu- ments that will be delivered to the function. There read more..

  • Page - 34

    18 | Chapter 2: Grammar Array literals are a convenient notation for specifying new arrays. There will be more about array literals actionGoTo:74,in Chapter actionGoTo:74,6. There will be more about regular expressions in actionGoTo:81,Chapter actionGoTo:81,7. literal number literal string literal object literal array literal function regexp literal object literal name expression string : {} , array read more..

  • Page - 35

    Functions | 19 Functions A function literal defines a function value. It can have an optional name that it can use to call itself recursively. It can specify a list of parameters that will act as vari- ables initialized by the invocation arguments. The body of the function includes vari- able definitions and statements. There will be more about functions in actionGoTo:42,Chapter read more..

  • Page - 36

    20 Chapter 3 CHAPTER 3 Objects 3 Upon a homely object Love can wink. —William Shakespeare, The Two Gentlemen of Verona The simple types of JavaScript are numbers, strings, booleans (true and false ), null , and undefined . All other values are objects. Numbers, strings, and booleans are object-like in that they have methods, but they are immutable. Objects in JavaScript are mutable read more..

  • Page - 37

    Retrieval | 21 A property’s name can be any string, including the empty string. The quotes around a property’s name in an object literal are optional if the name would be a legal JavaScript name and not a reserved word. So quotes are required around "first- name" , but are optional around first_name . Commas are used to separate the pairs. A property’s value can read more..

  • Page - 38

    22 | Chapter 3: Objects Update A value in an object can be updated by assignment. If the property name already exists in the object, the property value is replaced: stooge['first-name'] = 'Jerome'; If the object does not already have that property name, the object is augmented: stooge['middle-name'] = 'Lester'; stooge.nickname = 'Curly'; flight.equipment = { model: 'Boeing 777' read more..

  • Page - 39

    Reflection | 23 } var another_stooge = Object.create(stooge); The prototype link has no effect on updating. When we make changes to an object, the object’s prototype is not touched: another_stooge['first-name'] = 'Harry'; another_stooge['middle-name'] = 'Moses'; another_stooge.nickname = 'Moe'; The prototype link is used only in retrieval. If we try to retrieve a property value from an object, read more..

  • Page - 40

    24 | Chapter 3: Objects Enumeration The for in statement can loop over all of the property names in an object. The enu- meration will include all of the properties—including functions and prototype prop- erties that you might not be interested in—so it is necessary to filter out the values youdon’t want. The most common filters are the hasOwnProperty method and using typeof read more..

  • Page - 41

    Global Abatement | 25 delete another_stooge.nickname; another_stooge.nickname // 'Curly' Global Abatement JavaScript makes it easy to define global variables that can hold all of the assets of your application. Unfortunately, global variables weaken the resiliency of programs and should be avoided. One way to minimize the use of global variables is to create a single global variable read more..

  • Page - 42

    26 Chapter 4 CHAPTER 4 Functions 4 Why, every fault’s condemn’d ere it be done: Mine were the very cipher of a function... —William Shakespeare, Measure for Measure The best thing about JavaScript is its implementation of functions. It got almost every- thing right. But, as you should expect with JavaScript, it didn’t get everything right. A function encloses a set of read more..

  • Page - 43

    Invocation | 27 Function Literal Function objects are created with function literals: // Create a variable called add and store a function // in it that adds two numbers. var add = function (a, b) { return a + b; }; A function literal has four parts. The first part is the reserved word function . The optional second part is the function’s name. The function can read more..

  • Page - 44

    28 | Chapter 4: Functions The invocation operator is a pair of parentheses that follow any expression that pro- duces a function value. The parentheses can contain zero or more expressions, sepa- rated by commas. Each expression produces one argument value. Each of the argument values will be assigned to the function’s parameter names. There is no run- time error when the read more..

  • Page - 45

    Invocation | 29 variable of the outer function. A consequence of this error is that a method cannot employ an inner function to help it do its work because the inner function does not share the method’s access to the object as its this is bound to the wrong value. For- tunately, there is an easy workaround. If the method defines a variable and assigns it the value of read more..

  • Page - 46

    30 | Chapter 4: Functions // called get_status. Quo.prototype.get_status = function ( ) { return this.status; }; // Make an instance of Quo. var myQuo = new Quo("confused"); document.writeln(myQuo.get_status( )); // confused Functions that are intended to be used with the new prefix are called constructors.By convention, they are kept in variables with a capitalized name. read more..

  • Page - 47

    Return | 31 Arguments A bonus parameter that is available to functions when they are invoked is the arguments array. It gives the function access to all of the arguments that were sup- plied with the invocation, including excess arguments that were not assigned to parameters. This makes it possible to write functions that take an unspecified num- ber of parameters: // Make a read more..

  • Page - 48

    32 | Chapter 4: Functions Exceptions JavaScript provides an exception handling mechanism. Exceptions are unusual (but not completely unexpected) mishaps that interfere with the normal flow of a pro- gram. When such a mishap is detected, your program should throw an exception: var add = function (a, b) { if (typeof a !== 'number' || typeof b !== 'number') { read more..

  • Page - 49

    Augmenting Types | 33 Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; By augmenting Function.prototype with a method method, we no longer have to type the name of the prototype property. That bit of ugliness can now be hidden. JavaScript does not have a separate integer type, so it is sometimes necessary to extract read more..

  • Page - 50

    34 | Chapter 4: Functions Recursion A recursive function is a function that calls itself, either directly or indirectly. Recur- sion is a powerful programming technique in which a problem is divided into a set of similar subproblems, each solved with a trivial solution. Generally, a recursive func- tion calls itself to solve its subproblems. The Towers of Hanoi is a famous puzzle. read more..

  • Page - 51

    Recursion | 35 // Define a walk_the_DOM function that visits every // node of the tree in HTML source order, starting // from some given node. It invokes a function, // passing it each node in turn. walk_the_DOM calls // itself to process each of the child nodes. var walk_the_DOM = function walk(node, func) { func(node); node = node.firstChild; while read more..

  • Page - 52

    36 | Chapter 4: Functions }; document.writeln(factorial(4)); // 24 Scope Scope in a programming language controls the visibility and lifetimes of variables and parameters. This is an important service to the programmer because it reduces nam- ing collisions and provides automatic memory management: var foo = function ( ) { var a = 3, b = 5; var bar = read more..

  • Page - 53

    Closure | 37 Closure The good news about scope is that inner functions get access to the parameters and variables of the functions they are defined within (with the exception of this and arguments ). This is a very good thing. Our getElementsByAttribute function worked because it declared a results variable, and the inner function that it passed to walk_the_DOM also had access to read more..

  • Page - 54

    38 | Chapter 4: Functions var quo = function (status) { return { get_status: function ( ) { return status; } }; }; // Make an instance of quo. var myQuo = quo("amazed"); document.writeln(myQuo.get_status( )); This quo function is designed to be used without the new prefix, so the name is not read more..

  • Page - 55

    Closure | 39 Suddenly, the step function gets invoked again. But this time, fade ’s level is 2. fade returned a while ago, but its variables continue to live as long as they are needed by one or more of fade ’s inner functions. It is important to understand that the inner function has access to the actual vari- ables of the outer functions and not copies in order to read more..

  • Page - 56

    40 | Chapter 4: Functions Callbacks Functions can make it easier to deal with discontinuous events. For example, sup- pose there is a sequence that begins with a user interaction, making a request of the server, and finally displaying the server’s response. The naïve way to write that would be: request = prepare_the_request( ); response = send_request_synchronously(request); read more..

  • Page - 57

    Module | 41 lt: '<', gt: '>' }; // Return the deentityify method. return function ( ) { // This is the deentityify method. It calls the string // replace method, looking for substrings that start // with '&' and end with ';'. If the characters in // between are in the entity table, then replace the // read more..

  • Page - 58

    42 | Chapter 4: Functions // number, and a gensym method that produces unique // strings. var prefix = ''; var seq = 0; return { set_prefix: function (p) { prefix = String(p); }, set_seq: function (s) { seq = s; }, read more..

  • Page - 59

    Curry | 43 on('mousedown', function (m) { this.startDrag(m, this.getNinth(m)); }). on('mousemove', 'drag'). on('mouseup', 'stopDrag'). later(2000, function ( ) { this. color('yellow'). setHTML("What hath God wraught?"). slide(400, 40, read more..

  • Page - 60

    44 | Chapter 4: Functions Function.method('curry', function ( ) { var slice = Array.prototype.slice, args = slice.apply(arguments), that = this; return function ( ) { return that.apply(null, args.concat(slice.apply(arguments))); }; }); Memoization Functions can use objects to remember the results of previous operations, read more..

  • Page - 61

    Memoization | 45 result = fib(n - 1) + fib(n - 2); memo[n] = result; } return result; }; return fib; }( ); This function returns the same results, but it is called only 29 times. We called it 11 times. It called itself 18 times to obtain the previously memoized read more..

  • Page - 62

    46 Chapter 5 CHAPTER 5 Inheritance 5 Divides one thing entire to many objects; Like perspectives, which rightly gazed upon Show nothing but confusion... —William Shakespeare, The Tragedy of King Richard the Second Inheritance is an important topic in most programming languages. In the classical languages (such as Java), inheritance (or extends ) provides two useful services. First, it is read more..

  • Page - 63

    Pseudoclassical | 47 Pseudoclassical JavaScript is conflicted about its prototypal nature. Its prototype mechanism is obscured by some complicated syntactic business that looks vaguely classical. Instead of having objects inherit directly from other objects, an unnecessary level of indirection is inserted such that objects are produced by constructor functions. When a function object is created, read more..

  • Page - 64

    48 | Chapter 5: Inheritance Mammal.prototype.says = function ( ) { return this.saying || ''; }; Now, we can make an instance: var myMammal = new Mammal('Herb the Mammal'); var name = myMammal.get_name( ); // 'Herb the Mammal' We can make another pseudoclass that inherits from Mammal by defining its constructor function and replacing its prototype with an instance of read more..

  • Page - 65

    Pseudoclassical | 49 Our inherits and method methods return this , allowing us to program in a cascade style. We can now make our Cat with one statement. var Cat = function (name) { this.name = name; this.saying = 'meow'; }. inherits(Mammal). method('purr', function (n) { var i, s = ''; for (i = 0; i read more..

  • Page - 66

    50 | Chapter 5: Inheritance Object Specifiers It sometimes happens that a constructor is given a very large number of parameters. This can be troublesome because it can be very difficult to remember the order of the arguments. In such cases, it can be much friendlier if we write the constructor to accept a single object specifier instead. That object contains the specification read more..

  • Page - 67

    Prototypal | 51 Once we have an object that we like, we can make more instances with the Object. create method actionGoTo:36,from Chapter actionGoTo:36,3. We can then customize the new instances: var myCat = Object.create(myMammal); myCat.name = 'Henrietta'; myCat.saying = 'meow'; myCat.purr = function (n) { var i, s = ''; for (i = 0; i < n; i += 1) { read more..

  • Page - 68

    52 | Chapter 5: Inheritance Functional One weakness of the inheritance patterns we have seen so far is that we get no pri- vacy. All properties of an object are visible. We get no private variables and no private methods. Sometimes that doesn’t matter, but sometimes it matters a lot. In frustration, some uninformed programmers have adopted a pattern of pretend privacy. If they read more..

  • Page - 69

    Functional | 53 The my object is a container of secrets that are shared by the constructors in the inheritance chain. The use of the my object is optional. If a my object is not passed in, then a my object is made. Next, declare the private instance variables and private methods for the object. This is done by simply declaring variables. The variables and inner functions read more..

  • Page - 70

    54 | Chapter 5: Inheritance that.says = function ( ) { return spec.saying || ''; }; return that; }; var myMammal = mammal({name: 'Herb'}); In the pseudoclassical pattern, the Cat constructor function had to duplicate work that was done by the Mammal constructor. That isn’t necessary in the functional pattern because the Cat constructor will read more..

  • Page - 71

    Parts | 55 var coolcat = function (spec) { var that = cat(spec), super_get_name = that.superior('get_name'); that.get_name = function (n) { return 'like ' + super_get_name( ) + ' baby'; }; return that; }; var myCoolCat = coolcat({name: 'Bix'}); var name = myCoolCat.get_name( ); // 'like meow Bix read more..

  • Page - 72

    56 | Chapter 5: Inheritance // If an array of handlers exist for this event, then // loop through it and execute the handlers in order. if (registry.hasOwnProperty(type)) { array = registry[type]; for (i = 0; i < array.length; i += 1) { handler = array[i]; // A handler read more..

  • Page - 73

    Parts | 57 In this way, a constructor could assemble objects from a set of parts. JavaScript’s loose typing is a big benefit here because we are not burdened with a type system that is concerned about the lineage of classes. Instead, we can focus on the character of their contents. If we wanted eventuality to have access to the object’s private state, we could pass it read more..

  • Page - 74

    58 Chapter 6 CHAPTER 6 Arrays 6 Thee I’ll chase hence, thou wolf in sheep’s array. —William Shakespeare, The First Part of Henry the Sixth An array is a linear allocation of memory in which elements are accessed by inte- gers that are used to compute offsets. Arrays can be very fast data structures. Unfor- tunately, JavaScript does not have anything like this kind of read more..

  • Page - 75

    Length | 59 The object literal: var numbers_object = { '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine' }; produces a similar result. Both numbers and number_object are objects containing 10 properties, and those properties have exactly the same names and read more..

  • Page - 76

    60 | Chapter 6: Arrays The length can be set explicitly. Making the length larger does not allocate more space for the array. Making the length smaller will cause all properties with a sub- script that is greater than or equal to the new length to be deleted: numbers.length = 3; // numbers is ['zero', 'one', 'two'] A new element can be appended to the end of an array read more..

  • Page - 77

    Confusion | 61 Fortunately, the conventional for statement avoids these problems. JavaScript’s for statement is similar to that in most C-like languages. It is controlled by three clauses—the first initializes the loop, the second is the while condition, and the third does the increment: var i; for (i = 0; i < myArray.length; i += 1) { document.writeln(myArray[i]); } Confusion read more..

  • Page - 78

    62 | Chapter 6: Arrays Methods JavaScript provides a set of methods for acting on arrays. The methods are functions stored in Array.prototype . In actionGoTo:36,Chapter actionGoTo:36,3, we saw that Object.prototype can be aug- mented. Array.prototype can be augmented as well. For example, suppose we want to add an array method that will allow us to do com- putation on an array: read more..

  • Page - 79

    Dimensions | 63 // Give the data array a total function. data.total = function ( ) { return this.reduce(add, 0); }; total = data.total( ); // total is 108 Since the string 'total' is not an integer, adding a total property to an array does not change its length. Arrays are most useful when the property names are integers, but they are still objects, and read more..

  • Page - 80

    64 | Chapter 6: Arrays for (i = 0; i < n; i += 1) { my_array[i] = []; } // Note: Array.dim(n, []) will not work here. // Each element would get a reference to the same // array, which would be very bad. The cells of an empty matrix will initially have the value undefined . If youwant them to have a different initial value, you must explicitly set them. read more..

  • Page - 81

    65 Chapter 7 CHAPTER 7 Regular Expressions 7 Whereas the contrary bringeth bliss, And is a pattern of celestial peace. Whom should we match with Henry, being a king... —William Shakespeare, The First Part of Henry the Sixth Many of JavaScript’s features were borrowed from other languages. The syntax came from Java, functions came from Scheme, and prototypal inheritance came from read more..

  • Page - 82

    66 | Chapter 7: Regular Expressions Today’s regular expressions are not strictly regular, but they can be very useful. Reg- ular expressions tend to be extremely terse, even cryptic. They are easy to use in their simplest form, but they can quickly become bewildering. JavaScript’s regular expres- sions are difficult to read in part because they do not allow comments or read more..

  • Page - 83

    An Example | 67 In actionGoTo:21,Chapter actionGoTo:21,2, we used railroad diagrams to describe the JavaScript language. We can also use them to describe the languages defined by regular expressions. That may make it easier to see what a regular expression does. This is a railroad diagram for parse_url . Regular expressions cannot be broken into smaller pieces the way that functions read more..

  • Page - 84

    68 | Chapter 7: Regular Expressions It means repeat zero or one time. The (...) indicates a capturing group. A capturing group copies the text it matches and places it in the result array. Each capturing group is given a number. This first capturing group is 1, so a copy of the text matched by this capturing group will appear in result[1] . The [...] indicates a char- read more..

  • Page - 85

    An Example | 69 The $ represents the end of the string. It assures us that there was no extra material after the end of the URL. Those are the factors of the regular expression parse_url .* It is possible to make regular expressions that are more complex than parse_url ,but I wouldn’t recommend it. Regular expressions are best when they are short and sim- ple. Only then read more..

  • Page - 86

    70 | Chapter 7: Regular Expressions The i flag causes case to be ignored when matching letters. The only letter in our pattern is e . We want that e to also match E . We could have written the e factor as [Ee] or (?:E|e) , but we didn’t have to because we used the i flag: -? The ? suffix on the minus sign indicates that the minus sign is optional: \d+ \d read more..

  • Page - 87

    Construction | 71 Regular expression literals are enclosed in slashes. This can be a little tricky because slash is also used as the division operator and in comments. There are three flags that can be set on a RegExp . They are indicated by the letters g , i , and m , as listed in actionGoTo:87,Table actionGoTo:87,7-1. The flags are appended directly to the end of the read more..

  • Page - 88

    72 | Chapter 7: Regular Expressions RegExp objects made by regular expression literals share a single instance: function make_a_matcher( ) { return /a/gi; } var x = make_a_matcher( ); var y = make_a_matcher( ); // Beware: x and y are the same object! x.lastIndex = 10; document.writeln(y.lastIndex); // 10 Elements Let’s look more closely at the elements that make up read more..

  • Page - 89

    Elements | 73 Regexp Factor A regexp factor can be a character, a parenthesized group, a character class, or an escape sequence. All characters are treated literally except for the control characters and the special characters: \ / [ ] ( ) { } ? + * | . ^ $ which must be escaped with a \ prefix if they are to be matched literally. When in doubt, any special read more..

  • Page - 90

    74 | Chapter 7: Regular Expressions A simple letter class is [A-Za-z\u00C0-\u1FFF\u2800-\uFFFD] . It includes all of Uni- code’s letters, but it also includes thousands of characters that are not letters. Uni- code is large and complex. An exact letter class of the Basic Multilingual Plane is possible, but would be huge and inefficient. JavaScript’s regular expressions provide read more..

  • Page - 91

    Elements | 75 Noncapturing A noncapturing group has a (?: prefix. A noncapturing group simply matches; it does not capture the matched text. This has the advantage of slight faster perfor- mance. Noncapturing groups do not interfere with the numbering of capturing groups. Positive lookahead A positive lookahead group has a (?= prefix. It is like a noncapturing group except that after read more..

  • Page - 92

    76 | Chapter 7: Regular Expressions could be written as: (?:!|"|#|\$|%|&|'|\(|\)|\*|\+|,|-|\.|\/|:|;|<|=|>|@|\[|\\|]|\^|_|` |\{|\||\}|~) but is slightly more nicely written as: [!-\/:-@\[-`{-~] which includes the characters from ! through / and : through @ and [ through ` and { through ~ . It is still pretty nasty looking. The other convenience is the complementing of a class. If the read more..

  • Page - 93

    Elements | 77 ? is the same as {0,1} . * is the same as {0,} . + is the same as {1,} . Matching tends to be greedy, matching as many repetitions as possible up to the limit, if there is one. If the quantifier has an extra ? suffix, then matching tends to be lazy, attempting to match as few repetitions as possible. It is usually best to stick with the read more..

  • Page - 94

    78 Chapter 8 CHAPTER 8 Methods 8 Though this be madness, yet there is method in ’t. —William Shakespeare, The Tragedy of Hamlet, Prince of Denmark JavaScript includes a small set of standard methods that are available on the stan- dard types. Array array.concat(item…) The concat method produces a new array containing a shallow copy of this array with the item s appended to it. read more..

  • Page - 95

    Array | 79 array.pop( ) The pop and push methods make an array work like a stack. The pop method removes and returns the last element in this array . If the array is empty , it returns undefined . var a = ['a', 'b', 'c']; var c = a.pop( ); // a is ['a', 'b'] & c is 'c' pop can be implemented like this: Array.method('pop', function ( ) { return read more..

  • Page - 96

    80 | Chapter 8: Methods array.slice(start, end) The slice method makes a shallow copy of a portion of an array . The first element copied will be array[start] . It will stop before copying array[end] . The end parameter is optional, and the default is array.length . If either parameter is negative, array.length will be added to them in an attempt to make them nonnegative. If read more..

  • Page - 97

    Array | 81 // Function by takes a member name string and returns // a comparison function that can be used to sort an // array of objects that contain that member. var by = function (name) { return function (o, p) { var a, b; if (typeof o === 'object' && typeof p === 'object' && o && p) { read more..

  • Page - 98

    82 | Chapter 8: Methods // when the o[name] and p[name] are equal. var by = function (name, minor) { return function (o, p) { var a, b; if (o && p && typeof o === 'object' && typeof p === 'object') { a = o[name]; b = p[name]; if (a read more..

  • Page - 99

    Array | 83 insertCount = max(arguments.length - 2, 0), k = 0, len = this.length, new_len, result = [], shift_count; start = start || 0; if (start < 0) { start += len; } start = max(min(start, len), 0); read more..

  • Page - 100

    84 | Chapter 8: Methods unshift can be implemented like this: Array.method('unshift', function ( ) { this.splice.apply(this, [0, 0].concat(Array.prototype.slice.apply(arguments))); return this.length; }); Function function.apply(thisArg, argArray) The apply method invokes a function , passing in the object that will be bound to this and an optional array of arguments. read more..

  • Page - 101

    Number | 85 3e+0 3.14e+0 3.1415927e+0 3.1415926535897930e+0 3.141592653589793e+0 number.toFixed(fractionDigits) The toFixed method converts this number to a string in the decimal form. The optional fractionDigits parameter controls the number of decimal places. It should be between 0 and 20. The default is 0: document.writeln(Math.PI.toFixed(0)); document.writeln(Math.PI.toFixed(2)); document.writeln(Math.PI.toFixed(7)); read more..

  • Page - 102

    86 | Chapter 8: Methods // Produces 11.001001000011111101101010100010001000010110100011 3.1103755242102643 3.243f6a8885a3 3.141592653589793 Object object.hasOwnProperty(name) The hasOwnProperty method returns true if the object contains a property having the name . The prototype chain is not examined. This method is useless if the name is hasOwnProperty : var a = {member: true}; var b = Object.create(a); read more..

  • Page - 103

    RegExp | 87 var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g; var a, i; while ((a = tags.exec(text))) { for (i = 0; i < a.length; i += 1) { document.writeln(('// [' + i + '] ' + a[i]).entityify( )); } document.writeln( ); } // Result: // [0] <html> // [1] // [2] html // [3] // [0] <body bgcolor=linen> // [1] // read more..

  • Page - 104

    88 | Chapter 8: Methods // [2] p // [3] regexp.test(string) The test method is the simplest (and fastest) of the methods that use regular expressions. If the regexp matches the string , it returns true ; otherwise, it returns false . Do not use the g flag with this method: var b = /&.+;/.test('frank &amp; beans'); // b is true test could be implemented as: read more..

  • Page - 105

    String | 89 var text = 'Mississippi'; var p = text.indexOf('ss'); // p is 2 p = text.indexOf('ss', 3); // p is 5 p = text.indexOf('ss', 6); // p is -1 string.lastIndexOf(searchString, position) The lastIndexOf method is like the indexOf method, except that it searches from the end of the string instead of the front: var text = 'Mississippi'; var p = read more..

  • Page - 106

    90 | Chapter 8: Methods // [8] </p> // [9] </body> // [10] </html> string.replace(searchValue, replaceValue) The replace method does a search and replace operation on this string , producing a new string. The searchValue argument can be a string or a regular expression object. If it is a string, only the first occurrence of the searchValue is replaced, so: var read more..

  • Page - 107

    String | 91 return function ( ) { return this.replace(/[<>&"]/g, function (c) { return character[c]; }); }; }( )); alert("<&>".entityify( )); // &lt;&amp;&gt; string.search(regexp) The search method is like the indexOf method, except that it takes a regular expression object read more..

  • Page - 108

    92 | Chapter 8: Methods var text = 'last, first ,middle'; var d = text.split(/\s*,\s*/); // d is [ // 'last', // 'first', // 'middle' // ] There are some special cases to watch out for. Text from capturing groups will be included in the split: var e = text.split(/\s*(,)\s*/); // e is [ // 'last', // ',', // 'first', // ',', read more..

  • Page - 109

    String | 93 string.toUpperCase( ) The toUpperCase method produces a new string that is made by converting this string to uppercase. String.fromCharCode(char…) The String.fromCharCode function produces a string from a series of numbers. var a = String.fromCharCode(67, 97, 116); // a is 'Cat' read more..

  • Page - 110

    94 Chapter 9 CHAPTER 9 Style 9 Here is a silly stately style indeed! —William Shakespeare, The First Part of Henry the Sixth Computer programs are the most complex things that humans make. Programs are made up of a huge number of parts, expressed as functions, statements, and expres- sions that are arranged in sequences that must be virtually free of error. The runtime read more..

  • Page - 111

    Style | 95 JavaScript code is often sent directly to the public. It should always be of publication quality. Neatness counts. By writing in a clear and consistent style, your programs become easier to read. Programmers can debate endlessly on what constitutes good style. Most program- mers are firmly rooted in what they’re used to, such as the prevailing style where they went read more..

  • Page - 112

    96 | Chapter 9: Style which is an error that is very difficult to spot. It looks like: if (a) { b( ); c( ); } but it means: if (a) { b( ); } c( ); Code that appears to mean one thing but actually means another is likely to cause bugs. A pair of braces is really cheap protection against bugs that can be expensive to find. I always use read more..

  • Page - 113

    Style | 97 I want to avoid idioms that look like mistakes. I never allow switch cases to fall through to the next case. I once found a bug in my code caused by an unintended fall through immediately after having made a vigor- ous speech about why fall through was sometimes useful. I was fortunate in that I was able to learn from the experience. When reviewing the read more..

  • Page - 114

    98 Chapter 10 CHAPTER 10 Beautiful Features 10 Thus, expecting thy reply, I profane my lips on thy foot, my eyes on thy picture, and my heart on thy every part. Thine, in the dearest design of industry... —William Shakespeare, Love’s Labor’s Lost I was invited last year to contribute a chapter to Andy Oram’s and Greg Wilson’s Beautiful Code (O’Reilly), an anthology on read more..

  • Page - 115

    Beautiful Features | 99 Dynamic objects with prototypal inheritance Objects are class-free. We can add a new member to any object by ordinary assign- ment. An object can inherit members from another object. Object literals and array literals This is a very convenient notation for creating new objects and arrays. JavaScript literals were the inspiration for the JSON data interchange read more..

  • Page - 116

    100 | Chapter 10: Beautiful Features Features have a documentation cost. Every feature adds pages to the manual, increasing training costs. Features that offer value to a minority of users impose a cost on all users. So, in designing products and programming languages, we want to get the core features—the good parts—right because that is where we create most of the value. We read more..

  • Page - 117

    101 Appendix A APPENDIX A Awful Parts 1 That will prove awful both in deed and word. —William Shakespeare, Pericles, Prince of Tyre In this chapter, I present the problematic features of JavaScript that are not easily avoided. You must be aware of these things and be prepared to cope. Global Variables The worst of all of JavaScript’s bad features is its dependence on global read more..

  • Page - 118

    102 | Appendix A: Awful Parts The third is to use a variable without declaring it. This is called implied global: foo = value; This was intended as a convenience to beginners by making it unnecessary to declare variables before using them. Unfortunately, forgetting to declare a variable is a very common mistake. JavaScript’s policy of making forgotten variables global creates bugs read more..

  • Page - 119

    typeof | 103 Reserved Words The following words are reserved in JavaScript: abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch read more..

  • Page - 120

    104 | Appendix A: Awful Parts A bigger problem is testing a value for objectness. typeof cannot distinguish between null and objects, but you can because null is falsy and all objects are truthy: if (my_value && typeof my_value === 'object') { // my_value is an object or an array! } Also see the later sections “NaN” and “Phony Arrays.” Implementations disagree on read more..

  • Page - 121

    Phony Arrays | 105 Fortunately, integer arithmetic in floating point is exact, so decimal representation errors can be avoided by scaling. For example, dollar values can be converted to whole cents values by multiplying them by 100. The cents then can be accurately added. The sum can be divided by 100 to convert back into dollars. People have a reasonable expectation when they read more..

  • Page - 122

    106 | Appendix A: Awful Parts The typeof operator does not distinguish between arrays and objects. To determine that a value is an array, you also need to consult its constructor property: if (my_value && typeof my_value === 'object' && my_value.constructor === Array) { // my_value is an array! } That test will give a false negative if an array read more..

  • Page - 123

    Object | 107 undefined and NaN are not constants. They are global variables, and youcan change their values. That should not be possible, and yet it is. Don’t do it. hasOwnProperty In actionGoTo:36,Chapter actionGoTo:36,3, the hasOwnProperty method was offered as a filter to work around a problem with the for in statement. Unfortunately, hasOwnProperty is a method, not an operator, so read more..

  • Page - 124

    108 | Appendix A: Awful Parts constructor whose value is Object . The += operator, like the + operator, does concat- enation rather than addition when its operands are not numbers. Object is a func- tion, so += converts it to a string somehow and concatenates a 1 to its butt. We can avoid problems like this the same way we avoid problems with for in :by testing for read more..

  • Page - 125

    109 Appendix B APPENDIX B Bad Parts 2 And, I pray thee now, tell me for which of my bad parts didst thou first fall in love with me? —William Shakespeare, Much Ado About Nothing In this appendix, I present some of the problematic features of JavaScript that are easily avoided. By simply avoiding these features, you make JavaScript a better lan- guage, and yourself a better read more..

  • Page - 126

    110 | Appendix B: Bad Parts with Statement JavaScript has a with statement that was intended to provide a shorthand when accessing the properties of an object. Unfortunately, its results can sometimes be unpredictable, so it should be avoided. The statement: with (obj) { a = b; } does the same thing as: if (obj.a === undefined) { a = obj.b === undefined ? b read more..

  • Page - 127

    Block-less Statements | 111 frustrates JSLint (see actionGoTo:131,Appendix actionGoTo:131,C), so the tool’s ability to detect problems is signifi- cantly reduced. The eval function also compromises the security of your application because it grants too much authority to the eval ’d text. And it compromises the performance of the language as a whole in the same way that the with read more..

  • Page - 128

    112 | Appendix B: Bad Parts if (ok) t = true; can become: if (ok) t = true; advance( ); which looks like: if (ok) { t = true; advance( ); } but which actually means: if (ok) { t = true; } advance( ); Programs that appear to do one thing but actually do another are much harder to get right. A disciplined and read more..

  • Page - 129

    The function Statement Versus the function Expression | 113 In Java, the bitwise operators work with integers. JavaScript doesn’t have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and read more..

  • Page - 130

    114 | Appendix B: Bad Parts Typed Wrappers JavaScript has a set of typed wrappers. For example: new Boolean(false) produces an object that has a valueOf method that returns the wrapped value. This turns out to be completely unnecessary and occasionally confusing. Don’t use new Boolean or new Number or new String . Also avoid new Object and new Array . Use {} and [] read more..

  • Page - 131

    115 Appendix C APPENDIX C JSLint 3 What error drives our eyes and ears amiss? —William Shakespeare, The Comedy of Errors When C was a young programming language, there were several common program- ming errors that were not caught by the primitive compilers, so an accessory pro- gram called lint was developed that would scan a source file, looking for problems. As C matured, read more..

  • Page - 132

    116 | Appendix C: JSLint Undefined Variables and Functions JavaScript’s biggest problem is its dependence on global variables, particularly implied global variables. If a variable is not explicitly declared (usually with the var statement), then JavaScript assumes that the variable was global. This can mask mis- spelled names and other problems. JSLint expects that all variables and read more..

  • Page - 133

    Options | 117 /*members doTell, iDoDeclare, mercySakes, myGoodness, ohGoOn, wellShutMyMouth */ Options The implementation of JSLint accepts an option object that allows youto determine the subset of JavaScript that is acceptable to you. It is also possible to set those options within the source of a script. An option specification can look like this: /*jslint nomen: true, evil: read more..

  • Page - 134

    118 | Appendix C: JSLint Semicolon JavaScript uses a C-like syntax, which requires the use of semicolons to delimit state- ments. JavaScript attempts to make semicolons optional with a semicolon insertion mechanism. This is dangerous. Like C, JavaScript has ++ and -- and ( operators, which can be prefixes or suffixes. The disambiguation is done by the semicolon. In JavaScript, a read more..

  • Page - 135

    Forbidden Blocks | 119 JSLint allows you to turn on the “Tolerate sloppy line breaking” (laxbreak) option. Semicolon insertion can mask copy/paste errors. If youalways break lines after oper- ators, then JSLint can do a better job of finding those errors. Comma The comma operator can lead to excessively tricky expressions. It can also mask some programming errors. JSLint expects to read more..

  • Page - 136

    120 | Appendix C: JSLint Expression Statements An expression statement is expected to be an assignment, a function/method call, or delete . All other expression statements are considered errors. for in Statement The for in statement allows for looping through the names of all of the properties of an object. Unfortunately, it also loops through all of the members that were inher- ited read more..

  • Page - 137

    == and != | 121 with Statement The with statement was intended to provide a shorthand in accessing members in deeply nested objects. Unfortunately, it behaves very badly when setting new mem- bers. Never use the with statement. Use a var instead. JSLint does not expect to see a with statement. = JSLint does not expect to see an assignment statement in the condition part read more..

  • Page - 138

    122 | Appendix C: JSLint Use of the === and !== operators is always preferred. There is a “Disallow == and != ” (eqeqeq) option, which requires the use of === and !== in all cases. Labels JavaScript allows any statement to have a label, and labels have a separate namespace. JSLint is stricter. JSLint expects labels only on statements that interact with break : switch , read more..

  • Page - 139

    Not Looked For | 123 void In most C-like languages, void is a type. In JavaScript, void is a prefix operator that always returns undefined . JSLint does not expect to see void because it is confusing and not very useful. Regular Expressions Regular expressions are written in a terse and cryptic notation. JSLint looks for prob- lems that may cause portability problems. It also read more..

  • Page - 140

    124 | Appendix C: JSLint HTML JSLint is able to handle HTML text. It can inspect the JavaScript content contained within <script>...</script> tags and event handlers. It also inspects the HTML content, looking for problems that are known to interfere with JavaScript: • All tag names must be in lowercase. • All tags that can take a close tag (such as </p> ) read more..

  • Page - 141

    125 Appendix D APPENDIX D Syntax Diagrams 4 Thou map of woe, that thus dost talk in signs! —William Shakespeare, The Tragedy of Titus Andronicus array literal expression [] , block {} statements break statement break name ; label case clause case statements : expression read more..

  • Page - 142

    126 | Appendix D: Syntax Diagrams disruptive statement break statement return statement throw statement do statement do ( expression while block ); escaped character \ " double quote ' single quote \ backslash / slash b backspace f formfeed n new line r carriage return t tab u 4 hexadecimal digits exponent e digit + E- read more..

  • Page - 143

    Syntax Diagrams | 127 expression literal delete expression refinement name expression () prefix operator expression expression expression infix operator expression expression ? : invocation refinement new expression invocation expression statement delete name = expression refinement invocation expression refinement += -= read more..

  • Page - 144

    128 | Appendix D: Syntax Diagrams for statement for ( expression statement ; initialization expression condition ; ) ) block expression statement increment name variable expression object in digit fraction . var statements function body } { statements name function literal parameters function body function if statement if ) expression ( block then block else read more..

  • Page - 145

    Syntax Diagrams | 129 infix operator || logical or * multiply / divide % modulo + add - subtract greater or equal >= less or equal <= > greater < less equal === not equal !== && logical and any digit except 0 digit integer 0 invocation expression ) ( , literal number literal string literal object literal array literal function regexp literal read more..

  • Page - 146

    130 | Appendix D: Syntax Diagrams letter name digit _ integer fraction exponent number literal object literal name expression string : {} , name parameters , ) ( prefix operator typeof type of + - ! to number negate logical not read more..

  • Page - 147

    Syntax Diagrams | 131 refinement name . [] expression regexp choice regexp sequence | regexp class [] any Unicode character except / and \ and [ and ] and ^ and - and control character ^ - regexp class escape regexp class escape any special character f \ formfeed n newline r carriage return t tab u 4 hexadecimal digits not D S W d digit s whitespace w word character literal b backspace read more..

  • Page - 148

    132 | Appendix D: Syntax Diagrams regexp escape any special character f \ formfeed n newline r carriage return t tab u 4 hexadecimal digits B not D S W b word boundary d digit s whitespace w word character literal back reference integer regexp factor any Unicode character except / and \ and [ and ] and ( and ) and { and } and ? and + and * and | and control read more..

  • Page - 149

    Syntax Diagrams | 133 regexp choice // g im regexp literal regexp quantifier ? * + { , } ? integer integer regexp sequence regexp factor regexp quantifier return statement return expression ; statements expression statement ; do statement for statement while statement switch statement if statement try statement disruptive statement name label : read more..

  • Page - 150

    134 | Appendix D: Syntax Diagrams any Unicode character except " and \ and control character string literal "" escaped character '' any Unicode character except ' and \ and control character escaped character switch statement switch ) expression ( default { case clause disruptive statement statements } : throw statement throw expression ; var statements name expression ; , = var while read more..

  • Page - 151

    Syntax Diagrams | 135 space tab line end any character except line end any character except * and / // * / */ whitespace read more..

  • Page - 152

    136 Appendix E APPENDIX E JSON 5 Farewell: the leisure and the fearful time Cuts off the ceremonious vows of love And ample interchange of sweet discourse, Which so long sunder’d friends shoulddwell upon: God give us leisure for these rites of love! Once more, adieu: be valiant, and speed well! —William Shakespeare, The Tragedy of Richard the Third JavaScript Object Notation read more..

  • Page - 153

    JSON Syntax | 137 A JSON string is wrapped in double quotes. The \ character is used for escapement. JSON allows the / character to be escaped so that JSON can be embedded in HTML <script> tags. HTML does not allow the sequence </ except to start the </script> tag. JSON allows <\/ , which produces the same result but does not confuse HTML. JSON numbers are read more..

  • Page - 154

    138 | Appendix E: JSON [ { "first": "Jerome", "middle": "Lester", "last": "Howard", "nick-name": "Curly", "born": 1903, "died": 1952, "quote": "nyuk-nyuk-nyuk!" JSON string read more..

  • Page - 155

    Using JSON Securely | 139 }, { "first": "Harry", "middle": "Moses", "last": "Howard", "nick-name": "Moe", "born": 1897, "died": 1975, "quote": "Why, you!" }, read more..

  • Page - 156

    140 | Appendix E: JSON There is another danger in the interaction between external data and innerHTML .A common Ajax pattern is for the server to send an HTML text fragment that gets assigned to the innerHTML property of an HTML element. This is a very bad practice. If the HTML text contains a <script> tag or its equivalent, then an evil script will run. This again read more..

  • Page - 157

    A JSON Parser | 141 text, error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, read more..

  • Page - 158

    142 | Appendix E: JSON if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { read more..

  • Page - 159

    A JSON Parser | 143 } error("Bad string"); }, white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }, read more..

  • Page - 160

    144 | Appendix E: JSON } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); read more..

  • Page - 161

    A JSON Parser | 145 case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); read more..

  • Page - 162

    read more..

  • Page - 163

    147 We’d like to hear your suggestions for improving our indexes. Send email to index@oreilly.com. Index Symbols actionGoTo:128,-- decrement operator, actionGoTo:128,112, 118, actionGoTo:138,122 actionGoTo:138,- negation operator, actionGoTo:138,122 actionGoTo:138,-- operator, confusing pluses and actionGoTo:138,minuses, actionGoTo:138,122 actionGoTo:138,- subtraction operator, actionGoTo:138,122 actionGoTo:125,!= operator, actionGoTo:125,109, read more..

  • Page - 164

    148 | Index actionGoTo:137,assignment statement, actionGoTo:137,121 actionGoTo:48,augmenting types, actionGoTo:48,32 B actionGoTo:114,beautiful features, actionGoTo:114,98–100 actionGoTo:128,bitwise operators, actionGoTo:128,112, 122 actionGoTo:133,bitwise option (JSLint), actionGoTo:133,117 actionGoTo:22,block comments, actionGoTo:22,6, actionGoTo:112,96 actionGoTo:52,block scope, actionGoTo:52,36, 99 actionGoTo:127,blockless statements, actionGoTo:127,111 read more..

  • Page - 165

    Index | 149 actionGoTo:58,cascades, actionGoTo:58,42 actionGoTo:53,closure, actionGoTo:53,37–39 actionGoTo:59,curry method, actionGoTo:59,43 actionGoTo:48,exceptions, actionGoTo:48,32 actionGoTo:57,general pattern of a module, actionGoTo:57,41 actionGoTo:43,invocation, actionGoTo:43,27–30 actionGoTo:46,Apply Invocation Pattern, actionGoTo:46,30 actionGoTo:45,Constructor Invocation Pattern, actionGoTo:45,29 actionGoTo:44,Function Invocation Pattern, read more..

  • Page - 166

    150 | Index JSLint (continued) actionGoTo:138,continue statement, actionGoTo:138,122 actionGoTo:138,eval function, actionGoTo:138,122 actionGoTo:136,expression statements, actionGoTo:136,120 actionGoTo:136,for in statement, actionGoTo:136,120 actionGoTo:135,for statements, actionGoTo:135,119 actionGoTo:140,function report, actionGoTo:140,124 actionGoTo:132,functions, actionGoTo:132,116 actionGoTo:132,global declarations, actionGoTo:132,116 actionGoTo:132,global read more..

  • Page - 167

    Index | 151 actionGoTo:108,string.substring( ), actionGoTo:108,92 actionGoTo:108,string.toLocaleLowerCase( actionGoTo:108,), actionGoTo:108,92 actionGoTo:108,string.toLocaleUpperCase( actionGoTo:108,), actionGoTo:108,92 actionGoTo:108,string.toLowerCase( actionGoTo:108,), actionGoTo:108,92 actionGoTo:109,string.toUpperCase( actionGoTo:109,), actionGoTo:109,93 actionGoTo:81,that work with regular expressions, actionGoTo:81,65 actionGoTo:56,modules, read more..

  • Page - 168

    152 | Index actionGoTo:19,prototypal inheritance, actionGoTo:19,3 actionGoTo:45,prototypal inheritance actionGoTo:45,language, actionGoTo:45,29 actionGoTo:66,prototypal pattern, actionGoTo:66,50 actionGoTo:63,prototype property, actionGoTo:63,47 actionGoTo:49,prototypes of basic types, actionGoTo:49,33 actionGoTo:64,pseudoclass, creating, actionGoTo:64,48 actionGoTo:63,pseudoclassical actionGoTo:63,pattern actionGoTo:63,(inheritance), actionGoTo:63,47–49, read more..

  • Page - 169

    Index | 153 actionGoTo:26,for, actionGoTo:26,10, 12 actionGoTo:29,for in, actionGoTo:29,13 actionGoTo:26,if, actionGoTo:26,10 actionGoTo:30,labeled, actionGoTo:30,14 actionGoTo:30,loop, actionGoTo:30,14 actionGoTo:28,looping, actionGoTo:28,12 actionGoTo:30,return, actionGoTo:30,14 actionGoTo:26,switch, actionGoTo:26,10, 12, actionGoTo:28,14 actionGoTo:26,then block, actionGoTo:26,10 actionGoTo:30,throw, actionGoTo:30,14 actionGoTo:29,try, actionGoTo:29,13 read more..

  • Page - 170

    read more..

  • Page - 171

    About the Author Douglas Crockford is a senior JavaScript architect at Yahoo! who is well known for discovering and popularizing the JSON (JavaScript Object Notation) format. He is the world’s foremost living authority on JavaScript. He speaks regularly at confer- ences about advanced web technology, and he also serves on the ECMAScript committee. Colophon The animal on the cover of read more..

  • Page - 172

    read more..

Write Your Review