Skip to content

Instantly share code, notes, and snippets.

@bwiggs
Last active May 12, 2016 15:38
Show Gist options
  • Save bwiggs/ffbf3d1db567af0e9d684efe9531d0a3 to your computer and use it in GitHub Desktop.
Save bwiggs/ffbf3d1db567af0e9d684efe9531d0a3 to your computer and use it in GitHub Desktop.

http://codepen.io/anon/pen/zqbpNO?editors=0010

Printing Stuff out

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);

Create a plane object.

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.

2. Lets give our plane some properties

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);

Need a pilot!

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)

3. Boarding Passengers

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);

3. Prevent Overloading the plane

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++;
	}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment