You can think of objects as being similar to arrays except that you use identifiers to refer to the different parts of the structure instead of a numeric index.
Basics
Object literals are defined using curly brackets and a comma-separated list of key:value pairs.
Each key:value pair in the structure is a member.
You access the value of a member using dot notation: <object-name>.<key>
You can also access members using square-bracket array notation with a string as the index.
Keys can be any string. But if you want to use dot notation, keys must use the same name rules that apply to variables and functions.
Values can be anything: numbers, strings, Booleans, arrays, functions, other objects …
You can also create an object using the generic Object constructor (see below) and then add members manually:
This is the same as using an empty object literal, which is generally thought to be better:
You can add members on the fly no matter how you created the object:
Properties and methods
Objects are often used used to create a structure that describes something in terms of properties.
You can attach functions to an object as well. A function attached to an object is a method. The functions are usually defined with function literals.
Within a method, you can use the this keyword to refer to a member in the object.
Being able to define a structures that encapsulate a thing’s state (properties) and behavior (methods) is incredibly useful.
An object-oriented game
Below is a game built using basic object-oriented principles.
We define the requisiteWarrior entity using an object. The requisiteWarrior object bundles all the essential properties and behaviors relevant to the requisiteWarrior into one package.
Gameplay is simple loop that is easy to read thanks to the requisiteWarrior object.
The game is again quite lame. No skill, no strategy. Just pure chance. But it shows how objects can simplify writing the game.
Constructors
Sometimes, you need to create a bunch of objects that all have the same structure.
You might need several monsters.
You might need several pieces of candy.
Constructors are special functions that when invoked with the new keyword will make a new object based on a prototype template.
You might not be writing your own constructors for a while. However, most libraries and frameworks define constructors for you to use, so you must know how to use them.