




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Encontra documentos específicos para os exames da tua universidade
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Neste documento, aprenda a criar e manipular objetos em javascript, incluindo a criação de métodos e propriedades personalizadas. Saiba como converter valores primitivos em objetos e como herdar propriedades de objetos pai. Explore o uso de constructores de função e o prototype chain.
Tipologia: Manuais, Projetos, Pesquisas
1 / 130
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Foreword by Daniel Jebaraj
There is no catch here. Syncfusion has a vested interest in this effort.
As a component vendor, our unique claim has always been that we offer deeper and broader frameworks than anyone else on the market. Developer education greatly helps us market and sell against competing vendors who promise to “enable AJAX support with one click,” or “turn the moon to cheese!”
If you have any topics of interest, thoughts, or feedback, please feel free to send them to us at [email protected].
We sincerely hope you enjoy reading this book and that it helps you better understand the topic of study. Thank you for reading.
Please follow us on Twitter and “Like” us on Facebook to help us spread the word about the Succinctly series!
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 they pertain 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.
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 a 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.
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 toward the up-and-coming ECMA-262 Edition 5.
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.
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.
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 understand a programming concept.
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 some authors often make about their readers. Yes, both approaches can be annoying depending upon what knowledge the author brings to the subject, but they can also serve a useful purpose for those who want to learn a subject in detail.
Code will be colored using the normal JavaScript syntax highlighting in Visual Studio. This will help you understand the code, but you will be just fine reading this material on a monochrome e-book reader such as the Kindle Touch.
In addition to syntax highlighting the code, the text in this book is colored so as to distinguish between JavaScript words and keywords, JavaScript code, and regular text. The following excerpt from the book demonstrates this coloring semantic.
“Consider that the cody object created from the Object() constructor function is not really different from a string object created via the String() constructor function. To drive this fact home, examine and contrast the following code:”
Notice the use of gray italicized text for code references, orange text for JavaScript words and keywords, and regular black text for everything in-between.
Chapter 1 JavaScript 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 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 similar to the parts contained in the "cody” table. Translating the cody table into an actual JavaScript object would look like this:
Sample: sample01.html
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 giving 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 would look like so:
Sample: sample02.html
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 predefined objects. In the case of the cody object, I used the Object() constructor function to produce an empty object which I named cody. Because cody is an object constructed from the Object() constructor, we call cody an Object() object. What you really need to understand, beyond the creation of a simple Object() object like cody , is that the majority of values
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 that follows, 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 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 previous 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 that follow, showing that codyA and codyB have the same object values even though they are produced in different ways.
Sample: sample05.html
/* 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; }; };
var codyB = new Person(true, 33, 'male');
console.log(codyB); // Logs Object {living=true, age=33, gender="male", ...}
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 produced codyB , but can also be used as a powerful, centrally defined object "factory" to be used for creating more Person() objects. Crafting your 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 most commonly used for constructing objects.
JavaScript is really just a language that is prepackaged with a few native object constructors used to produce complex objects which express a very specific type of value (e.g., numbers, strings, functions, objects, 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.
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." (For example, 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