Undead Objects
JavaScript is an object-oriented language, but differently so than other, more "classically" object-oriented languages, like C, C++, Java, C#, and so on. For JavaScript, an object is an encapsulation. It takes a thing and sort of builds it in code, keeping track of information about the object (properties) and things the object can do/has done (methods). To borrow the metaphor from the previous book where a variable is a bucket in which you can put things, an object is more like a bucket filled with smaller buckets called properties. These are an object's own personal variables and represent information about the object, and they also come with a set of instructions on how those buckets can interact or what can be put in those buckets (these instructions are called methods and are like an object's personal functions).
For instance, we can create an object zombie.
There are many properties or things we can keep track of for the zombie, like its name, number of appendages, level of halitosis, days since turned, and favorite meal.
Name: Stuart
Appendages: 4
Halitosis: high
Days: 37
Meal: braaains
To write this in code, the object "zombie" would be:
Code snippet
let zombie = {name: 'Stuart',appendages: 4,halitosis: 'high',days: 37,meal: 'braaains'}
Then, to access or set the properties, you could use the bracket notation used in arrays. Here's how to set the properties:
Code snippet
let zombie1;zombie1['name'] = 'Sally';zombie1['appendages'] = 3;zombie1['halitosis'] = 'low';zombie1['days'] = 21;zombie1['meal'] = 'braaaaains';
You can also use the period operator. The period operator means that the text to the right is a property or method of the text to the left (if you're familiar with PHP, it's the same as the arrow -> operator). For instance:
Code snippet
let zombie2;zombie2.name = 'Bob';zombie2.appendages = 2;zombie2.halitosis = 'medium';zombie2.days = 122;zombie2.meal = 'braaaains';
Code snippet
document.write("Name: " + zombie1['name'] );prints: Sally
Code snippet
document.write("Number of Appendages: " + zombie2['appendages'] );prints: 2
Try it Out:
Codepen Demo:
Before we talk more about objects, let's take a side road and look at the switch statement to get one more zombie weapon under our belt. We'll also use it when we create methods.