3D Game Programming

(C. Jardin) #1
However, we do want to update the title and other information in our new
object. Let’s make this new object refer to a movie that’s a favorite of all 3D
programmers like us: Toy Story.

great_movie.title ='Toy Story';
great_movie.year = 1995;
great_movie.stars = ['Tom Hanks','Tim Allen'];
great_movie.aboutMe();
// => Toy Story, starring: Tom Hanks,Tim Allen

best_movie.aboutMe();
// => Star Wars, starring: Mark Hamill,Harrison Ford,Carrie Fisher

In the first three lines, we change the properties of the current object. Then
we tell the aboutMe() method to do its thing, which it does with the new infor-
mation that we just provided. This little bit of magic happens thanks to the
this keyword in aboutMe(). this.title always refers to the title property of the current
object.

Note that updating properties on the new great_movie object doesn’t affect the
best_movie object. best_movie has all of its properties unchanged and its aboutMe()
method still displays the original results.

All this talk of prototypes and prototypical objects is not just an excuse to
throw fancy words around. In fact, the concept of a prototype is very important
in JavaScript, and answers a question you may have had since the very first
chapter in this book: what’s that new keyword that we keep typing?

17.4 Constructing New Objects


We now have a good idea of what an object is in JavaScript. We also now see
how an object can be a prototypical object and act as a template for creating
similar objects. Creating new objects like this can be pretty tedious and mis-
take-prone. Consider this: if we forget to assign the year property on great_movie,
then the object will think Toy Story was made back in 1977. Unless we tell
the object differently, it copies all properties from the original (star_wars) object,
including the year, 1977!

We can also use a simple function to build objects in JavaScript—yes, the
simple function that we first saw all the way back in Chapter 5, Functions:
Use and Use Again, on page 49. Surprisingly, we don’t have to do anything
special to a function to create new objects. Normally, as a style thing, program-
mers capitalize the name of a function if it creates new objects. For example,
a function that will create movie objects might be called Movie.

Chapter 17. Project: Learning about JavaScript Objects • 162


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf