Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Introdução à programação JavaScript: Criando e manipulando objetos, Manuais, Projetos, Pesquisas de Engenharia Informática

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

2016

Compartilhado em 23/11/2016

thiago-souza-cjt
thiago-souza-cjt 🇧🇷

4.5

(34)

75 documentos

1 / 130

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Introdução à programação JavaScript: Criando e manipulando objetos e outras Manuais, Projetos, Pesquisas em PDF para Engenharia Informática, somente na Docsity!

By

Cody Lindley

Foreword by Daniel Jebaraj

Table of Contents

  • The Story behind the Succinctly Series of Books
  • About the Author.....................................................................................................................
  • Introduction
    • Why did I write this book?
    • Who should read this book?
    • Why JavaScript 1.5 and ECMA-262 Edition 3?
    • Why didn't I cover the Date(), Error(), or RegEx() objects?
  • Preface
    • More code, less words..........................................................................................................
    • Exhaustive code and repetition.............................................................................................
    • Color-coding conventions
    • Code examples
  • Chapter 1 JavaScript Objects
    • Creating objects
    • JavaScript constructors create and return object instances
    • The native JavaScript object constructors
    • User-defined/non-native object constructor functions
    • Instantiating constructors using the new operator
    • Creating shorthand or literal values from constructors
    • Primitive (aka simple) values
    • The primitive values null, undefined, "string", 10, true, and false are not objects
    • How primitive values are stored/copied in JavaScript
    • Primitive values are equal by value
    • The string, number, and Boolean primitive values act like objects when used like objects
    • Complex (aka composite) values
    • How complex values are stored/copied in JavaScript
    • Complex objects are equal by reference...............................................................................
    • Complex objects have dynamic properties
    • The typeof operator used on primitive and complex values
    • Dynamic properties allow for mutable objects
    • All constructor instances have constructor properties that point to their constructor function
    • Verify that an object is an instance of a particular constructor function
    • instance properties) An instance created from a constructor can have its own independent properties (aka
    • The semantics of "JavaScript objects" and "Object() objects"
  • Chapter 2 Working with Objects and Properties
    • Complex objects can contain most of the JavaScript values as properties
    • Encapsulating complex objects in a programmatically beneficial way
    • Getting, setting, and updating an object's properties using dot notation or bracket notation
    • Deleting object properties
    • How references to object properties are resolved
    • Using hasOwnProperty to verify that an object property is not from the prototype chain
    • Checking if an object contains a given property using the in operator..................................
    • Enumerate (loop over) an object’s properties using the for in loop
    • Host objects and native objects
    • Enhancing and extending objects with Underscore.js
  • Chapter 3 String()
    • Conceptual overview of using the String() object
    • String() parameters...........................................................................................................
    • String() properties and methods
    • String object instance properties and methods
  • Chapter 4 Number()
    • Conceptual overview of using the Number() object
    • Integers and floating-point numbers
    • Number() parameters...........................................................................................................
    • Number() properties
    • Number object instance properties and methods
  • Chapter 5 Boolean()
    • Conceptual overview of using the Boolean() object
    • Boolean() parameters.........................................................................................................
    • Boolean() properties and methods
    • Boolean object instance properties and methods
    • Non-primitive false Boolean objects convert to true
    • Certain things are false, everything else is true
  • Chapter 6 Working with Primitive String, Number, and Boolean Values
    • Primitive/literal values are converted to objects when properties are accessed
    • You should typically use primitive string, number, and Boolean values
  • Chapter 7 Null
    • Conceptual overview of using the null value
    • typeof returns null values as "object"
  • Chapter 8 Undefined
    • Conceptual overview of the undefined value
    • scope JavaScript ECMA-262 Edition 3 (and later) declares the undefined variable in the global
  • Chapter 9 The Head/Global Object
    • Conceptual overview of the head object
    • Global functions contained within the head object
    • The head object vs. global properties and global variables
    • Referring to the head object
    • The head object is implied and typically not referenced explicitly
  • Chapter 10 Object()
    • Conceptual overview of using Object() objects
    • Object() parameters...........................................................................................................
    • Object() properties and methods
    • Object() object instance properties and methods
    • Creating Object() objects using "object literals"
    • All objects inherit from Object.prototype
  • Chapter 11 Function().........................................................................................................
    • Conceptual overview of using Function() objects
    • Function() parameters
    • Function() properties and methods
    • Function object instance properties and methods
    • Functions always return a value
    • Functions are first-class citizens (not just syntax, but values)
    • Passing parameters to a function
    • this and arguments values are available to all functions
    • The arguments.callee property
    • The function instance length property and arguments.length
    • Redefining function parameters
    • Return a function before it is done (i.e. cancel function execution)
    • Defining a function (statement, expression, or constructor)
    • Invoking a function (function, method, constructor, or call() and apply())
    • Anonymous functions
    • Self-invoking function expression
    • Self-invoking anonymous function statements
    • Functions can be nested
    • Passing functions to functions and returning functions from functions
    • Invoking function statements before they are defined (aka function hoisting)........................
    • A function can call itself (aka recursion)
  • Chapter 12 The this Keyword
    • Conceptual overview of this and how it refers to objects
    • How is the value of this determined?
    • The this keyword refers to the head object in nested functions
    • Working around the nested function issue by leveraging the scope chain
    • Controlling the value of this using call() or apply()
    • Using the this keyword inside a user-defined constructor function......................................
    • The keyword this inside a prototype method refers to a constructor instance
  • Chapter 13 Scope and Closures
    • Conceptual overview of JavaScript scope
    • JavaScript does not have block scope................................................................................
    • Use var inside of functions to declare variables and avoid scope gotchas
    • The scope chain (aka lexical scoping)
    • The scope chain lookup returns the first found value
    • Scope is determined during function definition, not invocation
    • Closures are caused by the scope chain
  • Chapter 14 Function Prototype Property
    • Conceptual overview of the prototype chain
    • Why care about the prototype property?
    • Prototype is standard on all Function() instances..........................................................
    • The default prototype property is an Object() object......................................................
    • property Instances created from a constructor function are linked to the constructor’s prototype
    • Last stop in the prototype chain is Object.prototype....................................................
    • The prototype chain returns the first property match it finds in the chain
    • property Replacing the prototype property with a new object removes the default constructor
    • Instances that inherit properties from prototype will always get the latest values
    • Replacing the prototype property with a new object does not update former instances
    • constructors........................................................................................................................ User-defined constructors can leverage the same prototype inheritance as native
    • Creating inheritance chains (the original intention)
  • Chapter 15 Array()
    • Conceptual overview of using Array() objects
    • Array() parameters
    • Array() properties and methods
    • Array object instance properties and methods
    • Creating arrays
    • Adding and updating values in arrays
    • Length vs. index
    • Defining arrays with a predefined length
    • Setting array length can add or remove values
    • Arrays containing other arrays (aka multidimensional arrays)
    • Looping over an array, backwards and forwards
  • Chapter 16 Math Function
    • Conceptual overview of the built-in Math object
    • Math properties and methods
    • Math is not a constructor function
    • Math has constants you cannot augment or mutate
  • Review

Free? What is the catch?

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!”

Let us know what you think

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.

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 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.

Why JavaScript 1.5 and 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 toward the up-and-coming ECMA-262 Edition 5.

Why didn't I cover the Date(), Error(), or 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.

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 understand 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 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.

Color-coding conventions

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

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 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.

JavaScript constructors create 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." (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