JavaScript Enlightenment Cody Lindley JavaScript Enlightenment by Cody Lindley Copyright © 2013 Cody Lindley. 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 (http://my.safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editors: Simon St. Laurent and Meghan Blanchette Proofreader: BIM Proofreading Services Production Editor: Kristen Borg Indexer: Ellen Troutman Zaig Cover Designer: Randy Comer Interior Designer: David Futato January 2013: First Edition Revision History for the First Edition: 2012-12-18 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449342883 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. JavaScript Enlightenment, the image of a Eurasian eagle owl, and related trade dress are trade‐ marks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-34288-3 [LSI] Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. JavaScript Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Creating Objects 1 JavaScript Constructors Construct and Return Object Instances 6 The JavaScript Native/Built-In Object Constructors 8 User-Defined/Non-Native Object Constructor Functions 9 Instantiating Constructors Using the new Operator 10 Creating Shorthand/Literal Values from Constructors 12 Primitive (a.k.a. Simple) Values 13 The Primitive Values null, undefined, “string”, 10, true, and false Are Not Objects 15 How Primitive Values Are Stored/Copied in JavaScript 16 Primitive Values Are Equal by Value 17 The String, Number, and Boolean Primitive Values Act Like Objects When Used Like Objects 18 Complex (a.k.a. Composite) Values 19 How Complex Values Are Stored/Copied in JavaScript 20 Complex Objects Are Equal by Reference 21 Complex Objects Have Dynamic Properties 22 The typeof Operator Used on Primitive and Complex Values 22 Dynamic Properties Allow for Mutable Objects 23 All Constructor Instances Have Constructor Properties that Point to Their Constructor Function 24 Verify that an Object Is an Instance of a Particular Constructor Function 26 An Instance Created From a Constructor Can Have Its Own Independent Properties (Instance Properties) 27 The Semantics of “JavaScript Objects” and “Object() Objects” 29 2. Working with Objects and Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 iii Complex Objects Can Contain Most of the JavaScript Values as Properties 31 Encapsulating Complex Objects in a Programmatically Beneficial Way 32 Getting/Setting/Updating an Object’s Properties Using Dot Notation or Bracket Notation 33 Deleting Object Properties 36 How References to Object Properties Are Resolved 36 Using hasOwnProperty, Verify That an Object Property Is Not From the Prototype Chain 39 Checking If an Object Contains a Given Property Using the in Operator 39 Enumerate (Loop Over) an Object’s Properties using the for in Loop 40 Host Objects versus Native Objects 41 Enhancing and Extending Objects with Underscore.js 43 3. Object(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Conceptual Overview of Using Object() Objects 45 Object() Parameters 46 Object() Properties and Methods 47 Object() Object Instance Properties and Methods 47 Creating Object() Objects Using “Object Literals” 48 All Objects Inherit From Object.prototype 49 4. Function(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Conceptual Overview of Using Function() Objects 51 Function() Parameters 52 Function() Properties and Methods 53 Function Object Instance Properties and Methods 53 Functions Always Return a Value 53 Functions Are First-Class Citizens (Not Just Syntax but Values) 54 Passing Parameters to a Function 55 this and arguments Values Available To All Functions 55 The arguments.callee Property 56 The Function Instance length Property and arguments.length 57 Redefining Function Parameters 58 Return a Function Before It Is Done (Cancel Function Execution) 58 Defining a Function (Statement, Expression, or Constructor) 59 Invoking a Function [Function, Method, Constructor, or call() and apply()] 60 Anonymous Functions 61 Self-Invoking Function Expression 61 Self-Invoking Anonymous Function Statements 62 Functions Can Be Nested 62 Passing Functions to Functions and Returning Functions from Functions 63 Invoking Function Statements Before They Are Defined (Function Hoisting) 64 iv | Table of Contents A Function Can Call Itself (Recursion) 64 5. The Head/Global Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Conceptual Overview of the Head Object 67 Global Functions Contained Within the Head Object 68 The Head Object versus Global Properties and Global Variables 68 Referring to the Head Object 70 The Head Object Is Implied and Typically Not Referenced Explicitly 70 6. The this Keyword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Conceptual Overview of this and How It Refers to Objects 73 How Is the Value of this Determined? 74 The this Keyword Refers to the Head Object in Nested Functions 76 Working Around the Nested Function Issue by Leveraging the Scope Chain 77 Controlling the Value of this Using call() or apply() 77 Using the this Keyword Inside a User-Defined Constructor Function 79 The this Keyword Inside a Prototype Method Refers to a Constructor Instance 80 7. Scope and Closures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Conceptual Overview of JavaScript Scope 83 JavaScript Does Not Have Block Scope 84 Use var Inside Functions to Declare Variables and Avoid Scope Gotchas 85 The Scope Chain (Lexical Scoping) 85 The Scope Chain Lookup Returns the First Found Value 87 Scope Is Determined During Function Definition, not Invocation 87 Closures Are Caused by the Scope Chain 88 8. Function Prototype Property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Conceptual Overview of the Prototype Chain 91 Why Care About the prototype Property? 92 Prototype Is Standard on All function() Instances 93 The Default prototype Property Is an Object() Object 93 Instances Created From a Constructor Function are Linked to the Constructor’s prototype Property 94 Last Stop in the prototype Chain is Object.prototype 95 The prototype Chain Returns the First Property Match It Finds in the Chain 96 Replacing the prototype Property with a New Object Removes the Default Constructor Property 96 Instances That Inherit Properties from the Prototype Will Always Get the Latest Values 97 Replacing the prototype Property with a New Object Does Not Update Former Instances 98 Table of Contents | v User-Defined Constructors Can Leverage the Same Prototype Inheritance as Native Constructors 99 Creating Inheritance Chains (the Original Intention) 100 9. Array(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Conceptual Overview of Using Array() Objects 103 Array() Parameters 104 Array() Properties and Methods 104 Array Object Instance Properties and Methods 105 Creating Arrays 105 Adding and Updating Values in Arrays 106 Length versus Index 107 Defining Arrays with a Predefined Length 107 Setting Array Length can Add or Remove Values 108 Arrays Containing Other Arrays (Multidimensional Arrays) 108 Looping Over an Array, Backwards and Forwards 109 10. String(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Conceptual Overview of Using the String() Object 111 String() Parameters 111 String() Properties and Methods 112 String Object Instance Properties and Methods 112 11. Number(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Conceptual Overview of Using the Number() Object 115 Integers and Floating-Point Numbers 116 Number() Parameters 116 Number() Properties 117 Number Object Instance Properties and Methods 117 12. Boolean(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Conceptual Overview of Using the Boolean() Object 119 Boolean() Parameters 120 Boolean() Properties and Methods 120 Boolean Object Instance Properties and Methods 121 Non-Primitive False Boolean Objects Convert to true 121 Certain Things Are false, Everything Else Is true 122 13. Working with Primitive String, Number, and Boolean Values. . . . . . . . . . . . . . . . . . . . . 123 Primitive/Literal Values Are Converted to Objects When Properties Are Accessed 123 vi | Table of Contents You Should Typically Use Primitive String, Number, and Boolean Values 125 14. Null. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Conceptual Overview of Using the null Value 127 typeof Returns null Values as “object” 127 15. Undefined. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Conceptual Overview of the undefined Value 129 JavaScript ECMAScript 3 Edition (and Later) Declares the undefined Variable in the Global Scope 130 16. Math Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Conceptual Overview of the Built-In Math Object 131 Math Properties and Methods 131 Math Is Not a Constructor Function 132 Math Has Constants You Cannot Augment/Mutate 133 A. Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 B. Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Table of Contents | vii