http://codepen.io/anon/pen/zqbpNO?editors=0010
As developers we need to be able to interact with out object and see what's going on inside them. We can use a console.log
to get data out of the code we write.
var name = 'brian';
console.log("Hello, ", name);
Let's create an object literal.
var cessna = {};
^^^^^^^^^^ variable called cessna
var cessna = {};
^^ this is an object literal
Objects in javascript are made up of keys
and values
.
- keys: the name of the object property we want to add
- values: the value of the property, the values can be a value, like a number or string, or it can be a behavior. We can add behaviors using functions. We'll look at functions in a bit.
var cessna = {
name: 'Plany McPlaneface',
isFull: false,
numSeats: 5
};
Lets print out these properties using console.log
so we can make sure it's working.
console.log("Number of seats: ", cessna.numSeats);
Lets add a pilot to out plane
var thePilot = {
name: "Quagmire"
};
var cessna = {
name: 'Plany McPlaneface',
isFull: false,
numSeats: 5,
pilot: thePilot
};
console.log("Pilot's name is: ", cessna.pilot.name)
We can also have objects within objects. Here is an alternate way to add a pilot to out plane object.
var cessna = {
name: 'Plany McPlaneface',
isFull: false,
numSeats: 5,
pilot: {
name: 'Quagmire'
}
};
console.log("Pilot's name is: ", cessna.pilot.name)
Lets give out plane some passengers.
Add a new property, numPassengers
?
var cessna = {
isFull: false,
numPassengers: 0,
numSeats: 5
};
Add a new Behavior, addPassenger
a passenger
var cessna = {
isFull: false,
numPassengers: 0,
numSeats: 5,
addPassenger: function() {
this.numPassengers++;
}
};
Boarding Passengers!
cessna.addPassenger();
Update our status report.
console.log("Current Capacity: ", cessna.numPassengers + '/' + cessna.numSeats);
There's a bug in our plane code! We can add more passengers than the number of seats we have! We need to fix that! Let's use a conditional to check the number of seats available. If there aren't any seats left, we'll use a console.error()
to print out an error.
update addPassenger
method
var cessna = {
isFull: false,
numPassengers: 0,
numSeats: 5,
addPassenger: function() {
if(this.numPassengers >= this.numSeats) {
console.error("too many passengers!")
return;
}
this.numPassengers++;
}
};