3D Game Programming

(C. Jardin) #1
functionMovie(title, stars) {
this.title = title;
this.stars = stars;
this.year = (newDate()).getFullYear();
}

This is just a normal function using the function keyword, a name Movie, and a
list of parameters (such as the movie title and the list of stars in the movie).
However, we do something different inside the object builder’s function defi-
nition than what we would normally do for functions. Instead of performing
calculations or changing values, we assign the current object’s properties. In
this case, we assign the current object’s title in this.title, the names of the actors
and actresses who starred in the movie, and even the year in the list of
properties.

Aside from assigning the this values, there really is nothing special about this
function. So how does it create objects? What makes it an object constructor
and not a regular function?

The answer is something we saw in the very first chapter of this book: the
new keyword. We don’t call Movie() the way we would a regular function. It’s an
object constructor, so we construct new objects with it by placing new before
the constructor’s name.

varkung_fu_movie =newMovie('Kung Fu Panda', ['Jack Black','Angelina Jolie']);

The Movie() in new Movie is the constructor function we defined. It needs two
parameters: the title (Kung Fu Panda), and a list of stars (Jack Black and
Angelina Jolie).

Then, thanks to the property assignments we made in the constructor func-
tion, we can access these properties just like we did with our previous objects.

console.log(kung_fu_movie.title);
// => Kung Fu Panda
console.log(kung_fu_movie.stars);
// => ['Jack Black', 'Angelina Jolie']
console.log(kung_fu_movie.year);
// => 2013

You might notice that the year of the Kung Fu Panda movie is wrong (it came
out in 2008). This is because our constructor only knows to set the year
property to the current year. If you are up for a challenge, change the con-
structor so that it takes a third argument—the year. If the year is set, then
use that instead of the current year in the constructor.

report erratum • discuss

Constructing New Objects • 163


Prepared exclusively for Michael Powell

Free download pdf