Now we know how the creators of our 3D JavaScript library write all of their
code, so we can write things like this:
varshape =newTHREE.SphereGeometry(100);
varcover =newTHREE.MeshNormalMaterial();
varball =newTHREE.Mesh(shape, cover);
SphereGeometry, MeshNormalMaterial, and Mesh are all constructor functions in the
Three.js library.
One mystery is solved, but one remains: if we’re using function constructors
to build objects, how can we make methods for those objects? The answer to
that is why we emphasized the word “prototype” in the previous section. To
create an aboutMe() method for the objects created with our Movie() constructor,
we define the method on the constructor’s prototype. That is, for a prototypical
movie, we want the aboutMe() method to look like the following.
Movie.prototype.aboutMe =function() {
console.log(this.title +', starring: '+ this.stars);
};
With that method in place, we can ask the kung_fu_movie the answer to aboutMe().
kung_fu_movie.aboutMe();
// => Kung Fu Panda, starring: Jack Black,Angelina Jolie
JavaScript objects can have any number of methods, like aboutMe(), but it’s
good to keep the number of methods small. If you find yourself writing more
than twelve or so methods, then it may be time for a second object with a
new constructor.
17.5 The Code So Far
If you would like to double-check the code in this chapter, go to Section A1.17,
Code: Learning about JavaScript Objects, on page 253.
18.7 What’s Next
Object-oriented programming is a tough thing to wrap your brain around. If
you understood everything in this chapter, then you’re doing better than I
did when I learned these concepts. If not everything made sense, don’t worry.
Examples we’ll play with in the next few games should help clarify things.
After you’ve written a game or two with objects, it might help to reread this
chapter. As the games you invent on your own get more and more sophisti-
cated, you’ll want to rely on objects to help organize your code.
Chapter 17. Project: Learning about JavaScript Objects • 164
Prepared exclusively for Michael Powell report erratum • discuss