3D Game Programming

(C. Jardin) #1
We won’t be creating visualizations in this chapter. Instead we’ll be creating
objects in ICE and looking at them in the JavaScript console. So be sure to
have the JavaScript console open.

17.2 Simple Objects


Programmers refer to things as objects. Anything that we can touch or talk
about in the real world can be described as an object in the computer world.
Consider movies, for instance. I think we can all agree that Star Wars is the
greatest movie of all time. Right? Well, here we describe Star Wars as a
JavaScript object:

varbest_movie = {
title:'Star Wars',
year: 1977
};

Even though it’s short, there’s a lot going on in that example. First of all, we
see that JavaScript has another use for curly braces other than just wrapping
function definitions and if statements. Curly braces can also wrap JavaScript
objects. Additionally, we see that JavaScript objects are just like numbers
and strings—they can be assigned to a variable (best_movie in this case).

More importantly, objects let us describe something in different ways. In this
case, we can describe a movie with a title, the movie’s director, and the year
in which the movie was made. The different pieces of information that we
might use to describe things are called attributes.

The attributes of an object can be anything. In our Star Wars example, the
attributes are strings and numbers. We could have used Booleans, lists, and
even functions.

varbest_movie = {
title:'Star Wars',
year: 1977,
stars: ['Mark Hamill','Harrison Ford','Carrie Fisher'],
aboutMe:function() {
console.log(this.title +', starring: ' + this.stars);
}
};
best_movie.aboutMe();
// => Star Wars, starring: Mark Hamill,Harrison Ford,Carrie Fisher

Calling the aboutMe() function on our best_movie objects will produce the “Star
Wars, starring...” message in the JavaScript console. This is what the
console.log() call does—it logs whatever we want to the JavaScript console.

Chapter 17. Project: Learning about JavaScript Objects • 160


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf