These free mini-courses will give you a strong foundation in web development. Track your progress and access advanced courses on HTML/CSS, Ruby and JavaScript for free inside our student portal.
Scroll down...
Objects are ways of grouping properties with behavior. If you imagined a car as an object, the amount of gas remaining and the engine's horsepower would be properties. These properties would then influence the car's behavior, such as how quickly and how far it could drive.
In this lesson, we are going to take a deeper look at how this wonderfully important construct works in JavaScript. But first, get your hands dirty over at Codecademy.
Work through Codecademy's Objects I section before returning here.
Objects can be created using object literal syntax. This means a series of comma-separated, key-value pairs listed between curly braces. It looks like this:
var train = { name: "Thomas" }
var clown = {
name: "Bobo",
age: 58
}
Keep in mind that the keys are always strings, despite the lack of surrounding double quotes. This means that in the object { 3: "Three" }
the 3
is, in fact, the string "3"
rather than the number.
You can access and assign new properties in two ways, using either dot notation or bracket notation.
// Our object
var objecto = { alive: true, numberOfArms: 30 }
// Dot notation
objecto.numberOfArms //=> 30
objecto.numberOfArms = 2
objecto.numberOfArms //=> 2
// Bracket notation
objecto["alive"] //=> true
objecto["alive"] = false
objecto["alive"] //=> false
Either way is acceptable, though you will more commonly see and use dot notation. However, if the key happens to contain a space, then you must use bracket notation.
var billy = { "best friend": "Bobby"}
billy["best friend"] //=> "Bobby"
A method is what we call a function defined on an object. It's really just the same as a function. Functions are assigned to objects the same as any other property.
var objecto = {
highFive: function() {
console.log("HI FIVE!")
}
}
objecto.highFive() //=> "HI FIVE!"
As you can see, a method is called just like any other function, except here we must first access the correct property.
Methods are able to access the properties of the objects they are called on by using the this
keyword.
var objecto = {
energy: 5,
highFive: function() {
if ( this.energy > 3) {
console.log("HIGH FIVE!")
} else {
console.log("low five.")
}
}
}
objecto.highFive() //=> "HI FIVE!"
objecto.energy = 1
objecto.highFive() //=> "low five"
this
uses the same dot or bracket notation as accessing or assigning object properties, only it dynamically refers to the owning object instead of a variable.
All in all, objects are relatively straightforward. There are some quirks around using this
, but to explain them now would only take us off track. You now know enough to work with objects in JavaScript. Let's keep going!