Intro to Object-Oriented JavaScript



Intro to Object-Oriented JavaScript

0 1


Intro-to-Object-Oriented-JavaScript

Slides for the Girl Develop It Philadelphia - Intro to Object-Oriented JavaScript class

On Github kpcs / Intro-to-Object-Oriented-JavaScript

Intro to Object-Oriented JavaScript

“Object-oriented programming is programming oriented towards objects.” - my coworker

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules":

  • We are here for you
  • Every question is important
  • Help each other
  • Have fun!

Welcome!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • Fun Question Of The Day ...

What we'll cover today

  • What is an object?
  • What are attributes and methods?
  • What is class-based inheritance?
  • What is prototype-based inheritance?
  • How do we create objects using inheritance in JavaScript?
  • How can we extend a prototype in JavaScript?
  • How do we write maintanable code?
  • How can we refactor a website's code with Object-Oriented JavaScript?

Warm up exercises

Goal: Understanding objects

  • Create an object with a couple properties. For example, you could make a “student” object with the properties “name” and “hometown”.
  • Use console.log() to print out a sentence that includes the properties of that object. For example, “[name] is from [hometown].”

Warm up exercises

Goal: Understanding functions

  • Create a function that takes at least one argument. For example, you could make an “announce” function that alerts “Important announcement:” followed by the argument.
  • Call your function with an argument of your choice. For example, you could announce “Dogs are cute”.

Warm up exercises

Goal: Understanding "this"

  • In HTML, create a link to the website of your choice. Using jQuery’s .click(), make clicking on the link alert the link’s “href”.

What is an "Object"?

In computer science, an object is a location in memory having a value and possibly referenced by an identifier. An object can be a variable, function, or data structure. [source: Wikipedia]

	var carObject = {
	    make: 'Volkswagen',
	    model: 'Rabbit',
	    drive: function() {
	        // Code that makes car go forward
	    }
	};
		

Attributes and Methods

When we talk about objects, we're interested in two main concepts:

  • Attributes - object characteristics
  • Methods - object functionality
	var carObject = {
	    make: 'Volkswagen',    // attribute
	    model: 'Rabbit',       // attribute
	    drive: function() {    // method
	        // Code that makes car go forward
	    }
	};
		

Group exercise: Shapes

Think about these geometric shapes:

circle, square, rectangle, star, rhombus, triangle

  • What are some attributes shared by all shapes?
  • What are some methods that can be applied to all shapes?
  • Are there any attributes or methods that are unique to only one shape? ... to some shapes?

Class-based inheritance

Imagine going shopping for a new car.

  • You go to the dealer with a concept of a "car" is.
  • You find a particular car with qualities you like.
  • You like the way it handles and drives.
  • You purchase this particular car.

In object-oriented terms, we say that you have purchased an instance of the class of objects known as cars.

Prototypal inheritance

Let's imagine another way of shopping for a new car.

  • You go to the dealer with an old car you already own.
  • You ask the dealer for a newer model of the same car.
  • The color, make, and model of the car are the same, but the handling is better than your old car.
  • You purchase this particular car.

In object-oriented terms, we say that you have purchased an instance of a car based off of a prototype, from which it inherited some attributes and methods.

Creating new objects

In JavaScript, we use a constructor function to initialize new objects, and we use the new keyword to call the constuctor.

	// Create a constructor function for new cars
	function Car() {
	    // Set attributes of all new cars
	    this.odometer = 0;
	}

	var myCar = new Car();

	// myCar can access properties we defined in Car
	console.log(myCar.odometer);    // 0
		

Adding Variables

	// Create a constructor function for new cars
	function Car(make, model, year) {
	    // Set the given attributes of this object
	    this.make = make;
	    this.model = model;
	    this.year = year;

	    // Set attributes of all new cars, independent of variables
	    this.odometer = 0;
	}

	var myCar = new Car('Volkswagen', 'Rabbit', 2006);

	// myCar can access properties we defined in Car
	console.log(myCar.odometer);    // 0
	console.log(myCar.make);        // Volkswagen
		

Extending the prototype

The prototype is the collection of all the attributes and methods that the object knows about.

The prototype property of an object is used primarily for inheritance: methods and attributes on a function's prototype property are available to instances of that function.

Extending the Prototype

	function Car() {
	    this.odometer = 0;
	}

	// Extend the prototype to define methods for new Cars
	Car.prototype.drive = function() {
	    this.odometer = this.odometer + 1;
	}

	// Instantiate a new Car
	var myCar = new Car();

	// myCar can access methods defined in the prototype
	console.log(myCar.odometer);    // 0
	myCar.drive();
	console.log(myCar.odometer);    // 1
		

Putting it all together

	// Create a constructor function for new cars
	function Car(make, model, year) {
	    this.make = make;
	    this.model = model;
	    this.year = year;

	    this.odometer = 0;
	}

	// Extend the prototype to define methods for new cars
	Car.prototype.drive = function() {
	    this.odometer = this.odometer + 1;
	}

	// Instantiate a new car
	var myCar = new Car('Volkswagen', 'Rabbit', 2006);
		

Coding exercise 1

Let's make our own constructors and objects! We'll be using an exercise put together by GDI Chicago:

http://bit.ly/10IsNhJ

Extending objects

Suppose you wanted an easy way to talk about different types of cars.

  • All cars start with a make, model, year, and odometer.
  • Sedan-type cars have 4 doors
  • Hatchback-type cars can have 3 doors or 5 doors

Creating a hatchback

We can create a constructor function for each sub-type of Car that inherits attributes and methods from Car.

	// Assume Car() is defined as before
	function Hatchback(make, model, year, doors) {
	    // Call the Car constructor on the attributes
	    // Important: "this" is the first argument
	    Car.call(this, make, model, year);

	    // Set Hatchback-specific properties
	    this.doors = doors;
	}

	// Tell the Hatchback to extend the Car object
	Hatchback.prototype = Object.create(Car.prototype);
		

Creating a hatchback

We can also create methods specific to Hatchback.

	function Hatchback(make, model, year, doors) {
	    Car.call(this, make, model, year);
	    this.doors = doors;
	}

	Hatchback.prototype = Object.create(Car.prototype);

	// Now add a Hatchback-specific function
	Hatchback.prototype.openHatch = function() {
	    console.log('You opened the hatch!');
	}

	var myHatch = new Hatchback('Volkswagen', 'Rabbit', 2006, 3);

	myHatch.drive();
	myHatch.openHatch();

		

Substitutability

Substitutability is a principle of object-oriented programming introduced by BarbaraLiskov in a 1987 conference keynote entitled “Data abstraction and hierarchy”.

In a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of that program.

Coding exercise 2

Let's extend our Video to make a MusicVideo! We'll be using another exercise put together by GDI Chicago:

http://bit.ly/1u91gSM

Uses for object-oriented programming

  • Model physical concepts more clearly in your code
  • Make your code easier to read
  • Create code that is more easily maintainable and reusable

Maintainable code

When creating an object using our Car constructor, we have to pass in our arguments in a very specific order: make, then model, then year.

	var myCar = new Car('Volkswagen', 'Rabbit', 2006);
		

This is annoying and hard to maintain.

There is a better way.

A single argument

Replace your list of arguments with a single argument.

	// The better way
	function Car(args) {
	    this.make = args.make;
	    this.model = args.model;
	    this.year = args.year;
	}

	// Instantiate your object
	// NOTE: You can now list the arguments in any order!
	var myCar = new Car({
	    model: 'Rabbit',
	    year: 2006,
	    make: 'Volkswagen'
	});
		

Optional default values

You can also provide default values for your arguments within the constructor.

	// Now, with defaults! 
	function Car(args) {
	    args = args || {};
	    this.make = args.make || 'Unknown';
	    this.model = args.model || 'Unknown';
	    this.year = args.year || 0;
	}

	// Instantiate your object
	// NOTE: Now there's a backup if you don't know a value
	var myCar = new Car({
	    make: 'Volkswagen',
	    year: 2006
	});
		

Coding exercise 3

Let's clean up our constructors using what we learned! We'll be using another exercise put together by GDI Chicago:

http://bit.ly/1qisUpV

Building HTML with OOJS

You can create objects that know how to interact with your website.

	// Assuming Car as defined before
	Car.prototype.displayOnWebsite = function() {
	    var $carinfo = $('<p></p>');
	    $carinfo.text('You are buying a ' + this.model);

	    var $list = $('#listofcars');
	    $list.append($carinfo);
	};
		

Refactoring

Once your website code is working correctly, it's a good idea to go back and refactor it. Refactoring is a process developers use to restructure their existing code to make it easier to read.

Although it takes time to refactor your code now, right now is when you're most familiar with what you wrote.

Coding exercise 4

Let's refactor some JavaScript using objects! We'll be using another exercise put together by GDI Chicago:

http://bit.ly/1uif79V

Regroup & Recap

  • What did you work on?
  • What was the most challenging part?
  • What did you learn?

What's next?

  • Lots of practice!
  • Intro to Model-View-Controller (MVC) frameworks
    • Your data goes in the "model"
    • The way to display that data goes in the "view"
    • The model and view talk to each other and your server-side data using the "controller"
  • Intro to Backbone, a particular MVC framework that provides an amazing infrastructure for routine tasks like message passing, event handling, and working with multiple models

Thank you for attending!

Please help us make this class better by completing this short survey:

http://bit.ly/GDI-OOjs

My contact info:

Tracy Russell, on Twitter: @green_t_russell

Intro to Object Oriented JavaScript -- Girl Develop It Philly --