JavaScript Enlightenment

Jan 3, 2017 | Publisher: edocr | Category: Technology |  | Collection: ebooks | Views: 6 | Likes: 1

JavaScript Enlightenment Cody Lindley First Edition, based on JavaScript 1.5, ECMA-262, Edition 3 Table of Contents .................................................................................................................................. About the Author 8 .................................................................................................................. About the Technical Editors 9 ................................................................................................................................ Michael Richardson 9 ......................................................................................................................................... Kyle Simpson 9 ........................................................................................................................................ Nathan Smith 9 .............................................................................................................................................. Ben Nadel 9 ........................................................................................................................................ Ryan Florence 10 ........................................................................................................................................ Nathan Logan 10 ......................................................................................................................................... Introduction 11 ...................................................................................................................... Why did I write this book? 11 .................................................................................................................... Who should read this book? 12 .............................................................................................. Why JavaScript 1.5 & ECMA-262 Edition 3? 12 ........................................................................... Why didn't I cover the Date(), Error(), RegEx() objects? 12 ................................................................................................................................................. Preface 13 ............................................................................................................................ More code, less words 13 ............................................................................................................... Exhaustive code and repetition 13 ....................................................................................................................... Color-coding Conventions 13 ....................................................................................................... jsFiddle, JS Bin, and Firebug lite-dev 14 ............................................................................................................. Chapter 1 - JavaScript Objects 15 ..................................................................................................................................... Creating objects 15 ................................................................... JavaScript constructors construct and return object instances 20 ..................................................................................... The JavaScript native/built-in object constructors 21 ................................................................................ User-defined/non-native object constructor functions 23 2 .................................................................................... Instantiating constructors using the new operator 24 .................................................................................. Creating shorthand/literal values from constructors 25 .................................................................................................................. Primitive (aka simple) values 27 ........................................ The primitive values null, undefined, "string", 10, true, and false are not objects 28 ................................................................................ How primitive values are stored/copied in JavaScript 29 .......................................................................................................... Primitive values are equal by value 30 ............................ The string, number, and boolean primitive values act like objects when used like objects 31 ............................................................................................................. Complex (aka composite) values 32 ................................................................................. How complex values are stored/copied in JavaScript 33 .................................................................................................. Complex objects are equal by reference 34 ................................................................................................ Complex objects have dynamic properties 35 ....................................................................... The typeof operator used on primitive and complex values 35 .......................................................................................... Dynamic Properties allow for mutable objects 36 ....................... All constructor instances have constructor properties that point to their constructor function 37 ...................................................... Verify that an object is an instance of a particular constructor function 39 .. An instance created from a constructor can have its own independent properties (aka instance properties) 40 ............................................................ The semantics between "JavaScript objects" vs. "Object() objects" 42 ............................................................................... Chapter 2 - Working with Objects and Properties 43 ................................................... Complex objects can contain most of the JavaScript values as properties 43 ......................................................... Encapsulating complex objects in a programmatically beneficial way 44 ................................ Getting/setting/updating an object's properties using dot notation or bracket notation 45 ....................................................................................................................... Deleting object properties 48 ..................................................................................... How references to object properties are resolved 48 ................................. Using hasOwnProperty, verify that an object property is not from the prototype chain 51 ........................................................ Checking if an object contains a given property using the in operator 51 ............................................................. Enumerate (loop over) an object’s properties using the for in loop 52 ................................................................................................................ Host objects vs. native objects 53 ................................................................................... Enhancing & extending objects with Underscore.js 54 ............................................................................................................................. Chapter 3 - Object() 57 ......................................................................................... Conceptual overview of using Object() objects 57 3 ............................................................................................................................... Object() parameters 58 ............................................................................................................. Object() properties and methods 58 ..................................................................................... Object() object instance properties and methods 59 ........................................................................................ Creating Object() objects using "object literals" 59 ................................................................................................. All objects inherit from Object.prototype 61 ......................................................................................................................... Chapter 4 - Function() 63 ...................................................................................... Conceptual overview of using Function() objects 63 ............................................................................................................................ Function() parameters 63 .......................................................................................................... Function() properties and methods 64 ..................................................................................... Function object instance properties and methods 65 .............................................................................................................. Functions always return a value 65 .................................................................... Functions are first-class citizens (not just syntax, but values) 66 ............................................................................................................. Passing parameters to a function 67 ..................................................................................... this & arguments values available to all functions 67 ............................................................................................................... The arguments.callee property 68 ....................................................................... The function instance length property & arguments.length 69 ............................................................................................................... Redefining function parameters 70 ............................................................ Return a function before it is done (i.e. cancel function execution) 70 ....................................................................... Defining a function (statement, expression, or constructor) 71 ...................................................... Invoking a function (function, method, constructor, or call() & apply()) 72 ............................................................................................................................. Anonymous functions 73 ............................................................................................................. Self-invoking function expression 73 .......................................................................................... Self-invoking anonymous function statements 74 ......................................................................................................................... Functions can be nested 74 ........................................................... Passing functions to functions & returning functions from functions 75 ............................................. Invoking function statements before they are defined (aka function hoisting) 76 ................................................................................................... A function can call itself (aka recursion) 77 ................................................................................................... Chapter 5 - The Head/Global Object 78 ................................................................................................... Conceptual overview of the head object 78 .................................................................................... Global functions contained within the head object 79 4 ........................................................................ The head object vs. global properties and global variables 79 ................................................................................................................... Referring to the head object 80 .............................................................. The head object is implied and typically not referenced explicitly 81 ............................................................................................................... Chapter 6 - The this Keyword 83 ........................................................................... Conceptual overview of this and how it refers to objects 83 ....................................................................................................... How is the value of this determined? 84 .................................................................. The this keyword refers to the head object in nested functions 85 ................................................... Working around the nested function issue by leveraging the scope chain 87 .................................................................................... Controlling the value of this using call() or apply() 87 .............................................................. Using the this keyword inside a user-defined constructor function 88 ............................................. The keyword this inside a prototype method refers to a constructor instance 90 ............................................................................................................... Chapter 7 - Scope & Closures 92 ................................................................................................. Conceptual overview of JavaScript scope 92 ...................................................................................................... JavaScript does not have block scope 93 .................................................... Use var inside of functions to declare variables and avoid scope gotchas 93 ...................................................................................................... The scope chain (aka lexical scoping) 94 ................................................................................ The scope chain lookup returns the first found value 96 ................................................................... Scope is determined during function definition, not invocation 96 ................................................................................................... Closures are caused by the scope chain 97 ............................................................................................. Chapter 8 - Function Prototype Property 99 ............................................................................................. Conceptual overview of the prototype chain 99 .................................................................................................. Why care about the prototype property? 100 ...................................................................................... Prototype is standard on all Function() instances 101 ................................................................................. The default prototype property is an Object() object 101 ................ Instances created from a constructor function are linked to the constructor’s prototype property 102 ................................................................................. Last stop in the prototype chain is Object.prototype 103 ................................................... The prototype chain returns the first property match it finds in the chain 104 .................... Replacing the prototype property with a new object removes the default constructor property 105 ........................................ Instances that inherit properties from prototype will always get the latest values 106 5 ............................... Replacing the prototype property with a new object does not update former instances 107 .................... User-defined constructors can leverage the same prototype inheritance as native constructors 108 ................................................................................... Creating inheritance chains (the original intention) 109 ............................................................................................................................... Chapter 9 - Array() 111 ........................................................................................... Conceptual overview of using Array() objects 111 ................................................................................................................................. Array() parameters 112 .................................................................................................................. Array() properties & methods 112 ............................................................................................. Array object instance properties & methods 112 ...................................................................................................................................... Creating arrays 113 .......................................................................................................... Adding & updating values in arrays 114 .................................................................................................................................... Length vs. index 115 ................................................................................................. Defining arrays with a predefined length 115 ......................................................................................... Setting array length can add or remove values 116 ................................................................... Arrays containing other arrays (aka multidimensional arrays) 117 ....................................................................................... Looping over an array, backwards and forwards 117 ............................................................................................................................ Chapter 10 - String() 119 ...................................................................................... Conceptual overview of using the String() object 119 ................................................................................................................................ String() parameters 119 .............................................................................................................. String() properties and methods 120 ......................................................................................... String object instance properties and methods 120 ......................................................................................................................... Chapter 11 - Number() 122 ................................................................................... Conceptual overview of using the Number() object 122 ....................................................................................................... Integers and floating-point numbers 122 ............................................................................................................................. Number() parameters 123 .............................................................................................................................. Number() properties 124 ...................................................................................... Number object instance properties and methods 124 ........................................................................................................................ Chapter 12 - Boolean() 125 ................................................................................... Conceptual overview of using the Boolean() object 125 ............................................................................................................................. Boolean() parameters 125 6 .......................................................................................................... Boolean() properties and methods 126 ...................................................................................... Boolean object instance properties and methods 126 .................................................................................. Non-primitive false boolean objects convert to true 127 ........................................................................................ Certain things are false, everything else is true 127 ............................................................... Working with Primitive String, Number and Boolean values 129 ............................................ Primitive/literal values are converted to objects when properties are accessed 129 ........................................................ You should typically use primitive string, number, and boolean values 130 .................................................................................................................................. Chapter 13 - Null 132 ............................................................................................. Conceptual overview of using the null value 132 ...................................................................................................... typeof returns null values as "object" 132 ........................................................................................................................ Chapter 14 - Undefined 134 ............................................................................................ Conceptual overview of the undefined value 134 .................... JavaScript ECMA-262 edition 3 (and later) declares the undefined variable in the global scope 135 .................................................................................................................. Chapter 15 - Math Function 136 ....................................................................................... Conceptual overview of the built in Math Object 136 ................................................................................................................. Math properties and methods 136 ........................................................................................................... Math is not a constructor function 137 ..................................................................................... Math has constants you cannot augment/mutate 137 .................................................................................................................................................. Review 138 ............................................................................................................................................ Conclusion 141 7 About the Author Cody Lindley is a client-side engineer (aka front-end developer) and recovering Flash developer. He has an extensive background working professionally (11+ years) with HTML, CSS, JavaScript, Flash, and client-side performance techniques as it pertains to web development. If he is not wielding client- side code he is likely toying with interface/interaction design or authoring material and speaking at various conferences. When not sitting in front of a computer, it is a sure bet he is hanging out with his wife and kids in Boise, Idaho – training for triathlons, skiing, mountain biking, road biking, alpine climbing, reading, watching movies, or debating the rational evidence for a Christian worldview. 8 About the Technical Editors Michael Richardson Michael Richardson is a web and application developer living in Boise, Idaho. Way back when, he got an MFA in creative writing from Sarah Lawrence and published a novel in 2003 called Plans for a Mushroom Radio. These days, when he's not spending quality time with his lovely wife and rascal kid, he's managing his little web-based application called Timeglider. Kyle Simpson Kyle Simpson is a JavaScript Systems Architect from Austin, TX. He focuses on JavaScript, web performance optimization, and "middle-end" application architecture. If something can't be done in JavaScript or web stack technology, he's probably bored by it. He runs several open-source projects, including LABjs, HandlebarJS, and BikechainJS. Kyle works as a Software Engineer on the Development Tools team for Mozilla. Nathan Smith Nathan Smith is a UX developer at HP. He holds a MDiv from Asbury Theological Seminary. He began building sites late last century and enjoys hand coding HTML, CSS, and JavaScript. He created the 960 Grid System, a design and CSS framework for sketching, designing, and coding page layouts. He also made Formalize, a JavaScript and CSS framework that endeavors to bring sanity to form styling. Ben Nadel Ben Nadel is the chief software engineer at Epicenter Consulting, a Manhattan-based web application development firm specializing in innovative custom software that transforms the way its clients do business. He is also an Adobe Community Professional as well as an Adobe Certified Professional in 9 Advanced ColdFusion. In his spare time, he blogs extensively about all aspects of obsessively thorough web application development at www.bennadel.com. Ryan Florence Ryan Florence is a front-end web developer from Salt Lake City, Utah and has been creating websites since the early 90's. He is especially interested in creating experiences that are pleasing to both the end user and the developer inheriting the project. Ryan is active in the JavaScript community writing plugins, contributing to popular JavaScript libraries, speaking at conferences & meet-ups, and writing about it on the web. He currently works as a Senior Technical Consultant at Clock Four. Nathan Logan Nathan Logan has been a professional web developer for 8 years.  His focus is on client-side technologies, but he also digs the server-side.  He currently works for Memolane, alongside the author of this book.  Personally, Nathan is blessed with a wonderful wife and son, and enjoys mountain biking, hot springs, spicy food, scotch, and Christian faith/theology. 10 Introduction This book is not about JavaScript design patterns or implementing an object-oriented paradigm with JavaScript code. It was not written to distinguish the good features of the JavaScript language from the bad. It is not meant to be a complete reference guide. It is not targeted at people new to programming or those completely new to JavaScript. Nor is this a cookbook of JavaScript recipes. Those books have been written. It was my intention to write a book to give the reader an accurate JavaScript worldview through an examination of native JavaScript objects and supporting nuances: complex values, primitive values, scope, inheritance, the head object, etc. I intend this book to be a short and digestible summary of the ECMA-262, Edition 3 specification, focused on the nature of objects in JavaScript. If you are a designer or developer who has only used JavaScript under the mantle of libraries (such as jQuery, Prototype, etc), it is my hope that the material in this book will transform you from a JavaScript library user into a JavaScript developer. Why did I write this book? First, I must admit that I wrote this book for myself. Truth be told, I crafted this material so I could drink my own Kool-Aid and always remember what it tastes like. In other words, I wanted a reference written in my own words used to jog my memory as needed. Additionally: ✴ Libraries facilitate a "black box" syndrome that can be beneficial in some regards but detrimental in others. Things may get done fast and efficiently but you have no idea how or why. And the how and why really matter when things go wrong or performance becomes an issue. The fact is that anyone who intends to implement a JavaScript library or framework when building a web application (or just a good signup form) ought to look under the hood and understand the engine. This book was written for those who want to pop the hood and get their hands dirty in JavaScript itself. ✴Mozilla has provided the most up-to-date and complete reference guide for JavaScript 1.5. I believe what is missing is a digestible document, written from a single point of view, to go along with their reference guide. It is my hope that this book will serve as a "what you need to know" manual for JavaScript values, detailing concepts beyond what the Mozilla reference covers. 11 ✴Version 1.5 of JavaScript is going to be around for a fair amount of time, but as we move towards the new additions to the language found in ECMA edition 5, I wanted to document the cornerstone concepts of JavaScript that will likely be perennial. ✴Advanced technical books written about programing languages are often full of monolithic code examples and pointless meanderings. I prefer short explanations that get to the point, backed by real code that I can run instantly. I coined a term, "technical thin-slicing," to describe what I am attempting to employ in this book. This entails reducing complex topics into smaller, digestible concepts taught with minimal words and backed with comprehensive/focused code examples. ✴Most JavaScript books worth reading are three inches thick. Definitive guides, like David Flaniganʼs certainly have their place, but I wanted to create a book that hones in on the important stuff without being exhaustive. Who should read this book? This book is targeted at two types of people. The first is an advanced beginner or intermediate JavaScript developer who wishes to solidify his or her understanding of the language through an in- depth look at JavaScript objects. The second type is JavaScript library veteran who is ready to look behind the curtain. This book is not ideal for newbies to programming, JavaScript libraries, or JavaScript itself. Why JavaScript 1.5 & ECMA-262 Edition 3? In this book, I focus on version 1.5 of JavaScript (equivalent to ECMA-262 Edition 3) because it is the most widely implemented version of JavaScript to date. The next version of this book will certainly be geared towards the up-and-coming ECMA-262 Edition 5. Why didn't I cover the Date(), Error(), RegEx() objects? Like I said, this book is not an exhaustive reference guide to JavaScript. Rather, it focuses on objects as a lens through which to understand JavaScript. So I have decided not to cover the Date(), Error(), or RegEx() objects because, as useful as they are, grasping the details of these objects will not make or break your general understanding of objects in JavaScript. My hope is that you simply apply what you learn here to all objects available in the JavaScript environment. 12 Preface Before you begin, it is important to understand various styles employed in this book. Please do not skip this section, because it contains important information that will aid you as you read the book. More code, less words Please examine the code examples in detail. The text should be viewed as secondary to the code itself. It is my opinion that a code example is worth a thousand words. Do not worry if youʼre initially confused by explanations. Examine the code. Tinker with it. Reread the code comments. Repeat this process until the concept being explained becomes clear. I hope you achieve a level of expertise such that well- documented code is all you need to grok a programming concept. Exhaustive code and repetition You will probably curse me for repeating myself and for being so comprehensive with my code examples. And while I might deserve it, I prefer to err on the side of being exact, verbose, and repetitive, rather than make false assumptions authors often make about their reader. Yes, both can be annoying, depending upon what knowledge you bring to the subject, but they can also serve a useful purpose for those who want to learn a subject in detail. Color-coding Conventions In the JavaScript code examples (example shown below), orange is used to highlight code directly relevant to the concept being discussed. Any additional code used to support the orange colored code will be green. The color gray in the code examples is reserved for JavaScript comments (example shown below). 13 // this is a comment about a specific part of the code var foo = 'calling out this part of the code'; In addition to code examples being color-coded, the text in this book is colored so as to denote JavaScript words/keywords v.s. JavaScript code v.s. regular text. Below, I take an excerpt from the book to demonstrate this coloring semantic. "Consider that the cody object created from the Object() constructor function (i.e var cody = new Object()) is not really different from a string object created via the String() constructor function. To drive this fact home, examine the code below:" Notice the use of gray italic text for code references, orange text for JavaScript words/keywords, and regular black text for everything in-between. jsFiddle, JS Bin, and Firebug lite-dev The majority of code examples in this book are linked to a corresponding jsFiddle page, where the code can be tweaked and executed online. The jsFiddle examples have been configured to use the Firebug lite-dev plugin so that the log function (i.e. console.log) will work in most any modern browser regardless of if the browser has its own console. Before reading this book make sure you are comfortable with the usage and purpose of console.log. In situations where jsFiddle & Firebug lite-dev caused complications with the JavaScript code JS Bin & Firebug Lite-dev will be used. I've tried to avoid a dependency on a browser console by using Firebug lite-dev but with certain code examples the solution itself gets in the way of code execution. In these situations the console built into your web browser will have to be leveraged to output logs. If you are not using a browser with a built in JavaScript console I would suggest upgrading or switching browsers. When JS Bin is used, keep in mind that the code has to be executed manually (clicking 'Render') which differs from the page load execution done by jsFiddle. 14 Chapter 1 - JavaScript Objects Creating objects In JavaScript, objects are king: Almost everything is an object or acts like an object. Understand objects and you will understand JavaScript. So let's examine the creation of objects in JavaScript. An object is just a container for a collection of named values (aka properties). Before we look at any JavaScript code, let's first reason this out. Take myself, for example. Using plain language, we can express in a table, a "cody": cody property: property value: living true age 33 gender male The word "cody" in the table above is just a label for the group of property names and corresponding values that make up exactly what a cody is. As you can see from the table I am living, 33, and a male. JavaScript, however, does not speak in tables. It speaks in objects, which are not unlike the parts contained in the "cody" table. Translating the above table into an actual JavaScript object would look like this: // create the cody object... var cody = new Object(); // then fill the cody object with properties (using dot notation) cody.living = true; cody.age = 33; live code: http://jsfiddle.net/javascriptenlightenment/ckVA5/ 15 cody.gender = 'male'; console.log(cody); // logs Object {living = true, age = 33, gender = 'male'} Keep this at the forefront of your mind: objects are really just containers for properties, each of which has a name and a value. This notion of a container of properties with named values (i.e. an object) is used by JavaScript as the building blocks for expressing values in JavaScript. The cody object is a value which I expressed as a JavaScript object by creating an object, giving the object a name, and then give the object properties. Up to this point, the cody object we are discussing has only static information. Since we are dealing with a programing language, we want to program our cody object to actually do something. Otherwise, all we really have is a database, akin to JSON. In order to bring the cody object to life, I need to add a property method. Property methods perform a function. To be precise, in JavaScript, methods are properties that contain a Function() object, whose intent is to operate on the object the function is contained within. If I were to update the cody table with a getGender method, in plain English it would look like this: cody object property: property value: living true age 33 gender male getGender return the value of gender Using JavaScript, the getGender method from the updated cody table above would look like so: var cody = new Object(); cody.living = true; cody.age = 33; cody.gender = 'male'; cody.getGender = function(){return cody.gender;}; live code: http://jsfiddle.net/javascriptenlightenment/3gBT4/ 16 console.log(cody.getGender()); // logs 'male' The getGender method, a property of the cody object, is used to return one of codyʼs other property values: the value "male" stored in the gender property. What you must realize is that without methods, our object would not do much except store static properties. The cody object we have discussed thus far is what is known as an Object() object. We created the cody object using a blank object that was provided to us by invoking the Object() constructor function. Think of constructor functions as a template or cookie cutter for producing pre-defined objects. In the case of the cody object I used the Object() constructor function to produce an empty object which I named cody. Now since cody is an object constructed from the Object() constructor, we call cody an Object() object. What you really need to grok, beyond the creation of a simple Object() object like cody, is that the majority of values expressed in JavaScript are objects (primitive values like "foo", 5, and true are the exception but have equivalent wrapper objects). Consider that the cody object created from the Object() constructor function is not really different from say a string object created via the String() constructor function. To drive this fact home, examine and contrast the code below: var myObject = new Object(); // produces an Object() object myObject['0'] = 'f'; myObject['1'] = 'o'; myObject['2'] = 'o'; console.log(myObject); // logs Object { 0="f", 1="o", 2="o"} var myString = new String('foo'); // produces a String() object console.log(myString); // logs foo { 0="f", 1="o", 2="o"} As it turns out, myObject and myString are both . . . objects! They both can have properties, inherit properties, and are produced from a constructor function. The myString variable containing the 'foo' string value seems to be as simple as it goes, but amazingly itʼs got an object structure under its surface. If you examine both of the objects produced you will see that they are identical objects in live code: http://jsfiddle.net/javascriptenlightenment/XcfC5/ 17 substance but not in type. More importantly I hope you begin to see that JavaScript uses objects to express values. - You might find it odd to see the string value 'foo' in the object form because typically a string is represented in JavaScript as a primitive value (e.g. var myString = 'foo';). I specifically used a string object value here to highlight that anything can be an object, including values that we might not typically think of as an object (i.e. string, number, boolean). Also, I think this helps explain why some say that everything in JavaScript can be an object. JavaScript bakes the String() and Object() constructor functions into the language itself to make the creation of a String() object and Object() object trivial. But you, as a coder of the JavaScript language, can also create equally powerful constructor functions. Below, I demonstrate this by defining a non-native custom Person() constructor function, so that I can create people from it. // define Person constructor function in order to create custom Person() objects later var Person = function(living, age, gender) { ! this.living = living; ! this.age = age; ! this.gender = gender; ! this.getGender = function() {return this.gender;}; }; // instantiate a Person object and store it in the cody variable var cody = new Person(true, 33, 'male'); console.log(cody); /* The String() constructor function below, having been defined by JavaScript, has the same pattern. Because the string constructor is native to JavaScript, all we have to do to get a string instance is instantiate it. But the pattern is the same whether we use native constructors like String() or user-defined constructors like Person(). */ // instantiate a String object stored in the myString variable var myString = new String('foo'); console.log(myString); The user-defined Person() constructor function can produce person objects, just as the native Notes live code: http://jsfiddle.net/javascriptenlightenment/zQDSw/ 18 String() constructor function can produce string objects. The Person() constructor is no less capable, and is no more or less malleable, than the native String() constructor or any of the native constructors found in JavaScript. Remember how the cody object we first looked at was produced from an Object(). Itʼs important to note that the Object() constructor function and the new Person() constructor shown in the last code example can give us identical outcomes. Both can produce an identical object with the same properties and property methods. Examine the two sections of code below, showing that codyA and codyB have the same object values, even though they are produced in different ways. // create a codyA object using the Object() constructor var codyA = new Object(); codyA.living = true; codyA.age = 33; codyA.gender = 'male'; codyA.getGender = function() {return codyA.gender;}; console.log(codyA); // logs Object {living=true, age=33, gender="male", ...} /* The same cody object is created below, but instead of using the native Object() constructor to create a one-off cody, we first define our own Person() constructor that can create a cody object (and any other Person object we like) and then instantiate it with "new". */ var Person = function(living, age, gender) { ! this.living = living; ! this.age = age; ! this.gender = gender; ! this.getGender = function() {return this.gender;}; }; // logs Object {living=true, age=33, gender="male", ...} var codyB = new Person(true, 33, 'male'); console.log(codyB); The main difference between the codyA and codyB objects is not found in the object itself, but in the constructor functions used to produce the objects. The codyA object was produced using an instance of the Object() constructor. The Person() constructor, constructed codyB but can also be used as a powerful, centrally defined object "factory" to be used for creating more Person() objects. Crafting your live code: http://jsfiddle.net/javascriptenlightenment/Du5YV/ 19 own constructors for producing custom objects also sets up prototypal inheritance for Person() instances. Both solutions resulted in the same complex object being created. Itʼs these two patterns that are the most commonly used for constructing objects. JavaScript is really just a language that is pre-packaged with a few native object constructors used to produce complex objects which express a very specific type of value (e.g. numbers, strings, functions, object, arrays etc...) as well as the raw materials via Function() objects for crafting user-defined object constructors (e.g. Person()). The end result—no matter the pattern for creating the object—is typically the creation of a complex object. Understanding the creation, nature, and usage of objects and their primitive equivalents is the focus of the rest of this book. JavaScript constructors construct and return object instances The role of a constructor function is to create multiple objects that share certain qualities and behaviors. Basically a constructor function is a cookie cutter for producing objects that have default properties and property methods. If you said, "A constructor is nothing more than a function," then I would reply, "You are correct — unless that function is invoked using the new keyword." (e.g. new String('foo')). When this happens, a function takes on a special role, and JavaScript treats the function as special by setting the value of this for the function to the new object that is being constructed. In addition to this special behavior, the function will return the newly created object (i.e this) by default instead of the value false. The new object that is returned from the function is considered to be an instance of the constructor function that constructs it. Consider the Person() constructor again, but this time read the comments in the code below carefully, as they highlight the effect of the new keyword. /* Person is a constructor function. It was written with the intent of being used with the new keyword. */ var Person = function Person(living, age, gender) { live code: http://jsfiddle.net/javascriptenlightenment/YPR6Q/ 20 ! // "this" below is the new object that is being created (i.e. this = new Object();) ! this.living = living; ! this.age = age; ! this.gender = gender; ! this.getGender = function() {return this.gender;}; ! // when the function is called with the new keyword "this" is returned instead of false }; // instantiate a Person object named cody var cody = new Person(true, 33, 'male'); // cody is an object and an instance of Person() console.log(typeof cody); // logs object console.log(cody); // logs the internal properties and values of cody console.log(cody.constructor); // logs the Person() function The above code leverages a user-defined constructor function (i.e. Person()) to create the cody object. This is no different from the Array() constructor creating an Array() object (e.g. new Array ()): // instantiate an Array object named myArray var myArray = new Array(); // myArray is an instance of Array // myArray is an object and an instance of Array() constructor console.log(typeof myArray); // logs object! What? Yes, arrays are type of object console.log(myArray); // logs [ ] console.log(myArray.constructor); // logs Array() In JavaScript, most values (excluding primitive values) involve objects being created, or instantiated, from a constructor function. An object returned from a constructor is called an instance. Make sure you are comfortable with these semantics, as well as the pattern of leveraging constructors to construct objects. The JavaScript native/built-in object constructors live code: http://jsfiddle.net/javascriptenlightenment/cKa3a/ 21 The JavaScript language contains nine native (or built-in) object constructors. These objects are used by JavaScript to construct the language, and by "construct" I mean these objects are used to express object values in JavaScript code, as well as orchestrate several features of the language. Thus, the native object constructors are multifaceted in that they produce objects, but are also leveraged in facilitating many of the languageʼs programming conventions. For example, functions are objects created from the Function() constructor, but are also used to create other objects when called as constructor functions using the new keyword. Below, I list the 9 native object constructors that come pre-packaged with JavaScript: ✴Number() ✴String() ✴Boolean() ✴Object() ✴Array() ✴ Function() ✴Date() ✴RegExp() ✴Error() JavaScript is mostly constructed from just these nine objects (as well as string, number, and boolean primitive values). Understanding these objects in detail is key to taking advantage of JavaScriptʼs unique programming power and language flexibility. - The Math object is the oddball here. It's a static object, rather than a constructor function, meaning you canʼt do this: var x = new Math(). But you can use it as if it has already been instantiated (e.g. Math.PI). Truly, Math is a just an object namespace set up by JavaScript to house math functions. - The native objects are sometimes referred to as "global objects" since they are the objects that JavaScript has made natively available for use. Do not confuse the term global object with the "head" global object that is the topmost level of the scope chain, for example, the window object in all web browsers. - The Number(), String(), and Boolean() constructors not only construct objects; they also provide a primitive value for a string, number and boolean, depending upon how the constructor is leveraged. If you called these constructors directly, then a complex object is returned. If you simply express a number, string, or boolean value in your code (primitive values like 5, "foo" and true), then the constructor will return a primitive value instead of a complex object value. Notes 22 User-defined/non-native object constructor functions As you saw with the Person() constructor, we can make our own constructor functions, from which we can produce not just one but multiple custom objects. Below, I present the familiar Person() constructor function: 

Author: Cody Lindley

"If you are a designer or developer who has only used JavaScript under the mantle of libraries (such as jQuery, Prototype, etc), it is my hope that the material in this book will transform you from a JavaScript library user into a JavaScript developer."

Publishing documents on edocr is a proven way to start demand generation for your products and services. Thousands of professionals and businesses publish marketing (brochures, data sheets, press releases, white papers and case studies), sales (slides, price lists and pro-forma agreements), operations (specifications, operating manuals, installation guides), customer service (user manuals) and financial (annual reports and financial statements) documents making it easier for prospects and customers to find content, helping them to make informed decisions. #SEO #leadgen #content #analytics

info@edocr.com
www.edocr.com

About edocr

I am an accomplished content marketing professional helping you to build your brand and business. In my current role, I fulfill a multi-faceted solution marketplace including: publishing and sharing your content, embedding a document viewer on your website, improving your content’s search engine optimization, generating leads with gated content and earning money by selling your documents. I gobble up documents, storing them for safekeeping and releasing the text for excellent search engine optimization, lead generation and earned income. 

Publishing documents on edocr.com is a proven way to start demand generation for your products and services. Thousands of professionals and businesses publish marketing, sales, operations, customer service and financial documents making it easier for prospects and customers to find content, helping them to make informed decisions.

Get publishing now!

×

Modal Header

Modal body