Objects
After number, Boolean, string, function and array, we arrive at the last type of value that you can stow in a variable: an object.
What would you use an object for?
Say you want to save people’s contact details. You might use an array for every person, and do something like this:
personA = ["Jackie", "Chan", "Actor", 1954, "www.jackiechan.com"]
personB = ["Chuck", "Norris", "Roundhouse kicker", 1940, "www.chucknorris.com"]
That’ll work, but you would have to remember which value goes where, e.g. ‘profession’ being the third one.
print personB[2]
» "Roundhouse kicker"
While arrays can contain different values, it’s hard to keep things organized. In an object, on the other hand, you can label the values, so that it’s easier to retrieve them.
personA =
firstName: "Jackie"
surname: "Chan"
profession: "Actor"
yearOfBirth: 1954
website: "www.jackiechan.com"
personB =
firstName: "Chuck"
surname: "Norris"
profession: "Roundhouse kicker"
yearOfBirth: 1940
website: "www.chucknorris.com"
print personA["surname"]
» "Chan"
The name you use (e.g., surname
) is called the ‘key,’ and the content behind it (e.g. "Chan"
) is called the ‘value.’ These key-value pairs are also called properties.
Remember the properties you set on those layer objects earlier?
layerA = new Layer
width: 350, height: 100
x: 200, y: 400
Framer’s layers are objects that come with a bunch of functionality already included. (It comes included because you create them with new Layer
.)
Since arrays can contain all types of values, including objects, we can gather our ‘person’ objects in an ‘address book’ array.
addressBook = [personA,personB]
# The ‘profession’ value of the 2nd object
print addressBook[1]["profession"]
» "Roundhouse kicker"
Recall that you can also write the property’s key using dot notation, e.g. .profession
, instead of ["profession"]
.
# Changing the value, now with ‘dot notation’
addressBook[1].profession = "Actor"
# Accessing the value with ‘dot notation’
print addressBook[1].profession
» "Actor"