Lesson 1: Creating JavaScript objects CHAPTER 6 263
an object and owned by the object. A method is a function that is defined on an object and
owned by the object.
Understanding the JavaScript object-oriented caveat
JavaScript is a very flexible language. You can create objects, but the relationship between the
JavaScript language and class-based, object-oriented programming is not direct. The most
glaring example is that there is no class keyword in JavaScript. If you’re familiar with class-
based, object-oriented programming, you’ll be struggling to find the “class.”
JavaScript is a prototype-based, object-oriented programming language. In JavaScript,
everything is an object, and you either create a new object from nothing, or you create an
object from a clone of an existing object, known as a prototype.
Conceptually, you can simulate class creation by using a function. Class-based, object-
oriented purists dislike the idea of a function being used to simulate a class. Keep an open
mind as patterns are presented. This lesson should give you what you need to accomplish
your tasks.
The problem you typically encounter is finding one correct solution for all scenarios. As
you read on, you’ll find that achieving proper encapsulation of private data requires you to
create copies of the functions that can access the private data for each object instance, which
consumes memory. If you don’t want to create copies of the method for each object instance,
the data needs to be publicly exposed, thus losing the benefits of encapsulation, by which
you hide object details that users shouldn’t need to see.
The general consensus of this issue of encapsulation versus wasteful memory consump-
tion is that most people would rather expose the data to minimize memory consumption. Try
to understand the benefits and drawbacks of each pattern when deciding which option to
implement in your scenario.
Using the JavaScript object literal pattern
Probably the simplest way to create an object in JavaScript is to use the object literal syntax.
This starts with a set of curly braces to indicate an object. Inside the curly braces is a comma-
separated list of name/value pairs to define each property. Object literals create an object
from nothing, so these objects contain precisely what you assign to them and nothing more.
No prototype object is associated with the created object. The following example demon-
strates the creation of two objects that represent vehicles.
var car1 = {
year: 2000,
make: 'Ford',
model: 'Fusion',
getInfo: function () {
return 'Vehicle: ' + this.year + ' ' + this.make + ' ' + this.model;
}
};
Key
Te rms