An object is a collection of properties, and a property is an association between a name and a value. A property’s value can be a function, in which case the property is known as a method.
There are two ways to access the properties of an object. The first is “dot notation.” Let’s initialize a variable with an object literal and then access its properties with dot notation.
Ok, so that’s pretty straight forward. Dot notation is the more common way to access object properties. It is the preferred method, assuming you know what properties you need access to. Note the return of
myObect.getName. Since we didn’t invoke the function, we simply get a reference to it. You can pass functions around like any other variable. Remember, they won’t be invoked unless we call them with opening and closing parenthesis, like this…
The second way to access an object’s properties is with “bracket notation.” It’s also pretty simple.
As you can see, this requires just a bit more typing and doesn’t read quite as nicely as dot notation (in my opinion), BUT this is more powerful. Bracket notation is what’s known as a “computed property accessor.” This means that whatever value is within the brackets is computed (or evaluated), before it accesses the object. So we can use variables or other expressions to dynamically access an object’s properties. This is not possible with dot notation.
You can also set properties with variables/expressions.
Okay, that’s pretty cool. Knowing this, if you wanted to get all the property values of an object, you might write a function like this…
And call it like so…
You could modify this and throw a callback into the mix…
If you’re confused by the callback function, I got you covered—read this. However, callbacks aren’t the focus of this. This is about computed accessors. They’re neat, you guys!