October 5

Objects

Javascript allows us to store multiple properties and values in a single place called an object.

So far, we have seen integers:

var x = 1; // an integer

We have seen strings:

var x = "a string"; // a string value

We have seen arrays:

var x = [1, 2, 3, "just to be different"]; // an array of values

Objects as Literals

Now, we introduce objects. An object can be created using "literal" syntax, in which all the properties and values are specified within braces {}:

var lecture = {title: "Objects", room: "DH A302", time: "12:30pm"};

Once we have an object, we can access different properties using the “dot” notation (remember, “dot” can be read “apostrophe-s” or “‘s”):

x.title // evaluates to "Objects"
x.room // evaluates to "DH A302"

You can also access properties using array subscript notation, but where the “index” is a string naming the property:

x["room"] // evaluates to "DH A302"

Objects by Construction

We can also construct objects bit-by-bit. This might be useful if the values depend on conditions or you are reading data from somewhere and storing it in properties of objects. First, we make a new empty object:

var y = new Object();

Next, we can store values into properties using assignment statements:

y.title = "Objects";
y.room = "DH A302";
y.time = "12:30pm";

Now x and y have the same properties and values. Are they equal?

x == y evaluates to false. Yes, the properties are all the same, but x and y are different objects so JavaScript says they are “not equal.” Can we have “equal” objects:

z = x; // assign x to z
print(z === x); // prints "true"!

In this case, z and x are said to reference the same object. There is only one object here but two different variables, z and x, both reference the same object and hence are considered to be equal. Changing z will change x — they are the same object:

z.title = "z title";
print(x); // prints {"title": "z title", "room": "DH A302", "time": "12:30pm"}

This is sometimes confusing, and we say that z is an alias for x and changing z has the side effect of changing x.

However, the advantage of objects working this way is that when we pass an object as a parameter, the object is not copied. Instead the parameter gets a reference to the same identical object, allowing the function to modify the object. When the function returns, the modifications are seen by the caller.

Here is a short program to draw a rectangle represented by properties of an object:

sketch

We can modify the object in the draw loop. (If the % operator is unfamiliar, look it up. It computes the remainder.)

sketch

Finally, here is an example where we pass objects as parameters to functions to draw and move the object. Notice how clean and elegant the draw function becomes:

sketch