3D Game Programming

(C. Jardin) #1
When we use functions in objects like this, we call them with a different name,
method. Methods let us change an object or, as we’re doing here, return some
other information about the object.

Take a look at the aboutMe() method and how we use the this keyword. The this
keyword is how we refer to the current object. If we’d used title instead of
this.title, we would have gotten an error message telling us that title was unde-
fined. In this example, title was undefined because the code was looking for
a variable named title somewhere else in the program. By using this.title, we are
specifying that we want the title property assigned to the current object.

console.log() Is Your Friend
Web programmers use console.log() all the time to double-check that
variables have the value we expect them to have. It never shows
up in the web page or the game, but programmers can see it—and
fix things if they are broken. Just remember to remove console.log()
when you’re done—it is much easier to use the JavaScript console
without a ton of console.log() messages!

17.3 Copying Objects


In real life, you copy a cool idea or thing by copying everything it does and
changing a few things here and there to make it even better. The thing you’re
copying becomes the prototype for the new way of doing it. JavaScript handles
copying objects in a similar way.

To describe another movie, we can copy the prototypical best_movie object by
using Object.create:

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

Object.create will create a new object with all the same properties and methods
of the prototypical object we created earlier. So the new object, great_movie, has
the same title and actors as the original best_movie. It also has the same aboutMe()
method.

We don’t need to make any changes to the aboutMe() method. We still want it
to log the movie title and the list of the stars to the JavaScript console. Even
if the title and list of stars changes, the aboutMe() method stays the same—it
may log different information, but it will use the same properties to do so.

report erratum • discuss

Copying Objects • 161


Prepared exclusively for Michael Powell

Free download pdf