Object-Oriented Programming (OOP)

…in JavaScript is really

“Object-oriented” JavaScript

JavaScript is not a strict OO language like Java, but we can still use it in an object-oriented way.

What is Object-Oriented Programming?

  • Object Oriented Programming is one of many programming approaches: procedural, event-driven, declarative...
  • All this means is that programs are organized around objects (data & functions).
  • You might choose OOP because Objects make things easier to understand and act as a natural way to break your code into modules. When a large code base is composed of many small Objects, it is easier to maintain and change.

Why use OOP?


Easy to Understand

Without seeing my code, you can probably guess what an object called Bike can do (or not do)

via GIPHY

Why use OOP?


Encapsulation

a fancy way of saying "put all of my properties/behaviors in one place where other objects can't touch them"

via GIPHY

Why use OOP?


Inheritance

Just as you inherited traits from you mom, your objects may inherit traits from other objects

via GIPHY

JavaScript Object Prototypes

Every object in JavaScript has a prototype.

All JavaScript objects inherit their properties and their functions from their prototype.

This is called prototypal inheritance

Object Prototypes

We know that when we create a new array:

  • It will have a length property
  • It will have a map() function
  • It will have a filter() function
  • It will have a join() function

An array inherits these properties and functions from an Array prototype that defines what an array is (properties) and what it can do (functions)

Object Prototype Example

Let's use a book as an example of an object prototype.

Book prototype

Properties:

  • title
  • author
  • pages

Function:

  • read()

Object Prototype Instances

There can be many instances of object prototypes:

Kindred

by Octavia Butler

264 pages

The Handmaid's Tale

by Margaret Atwood

311 pages

A Wrinkle in Time

by Madeline L'Engle

211 pages

Each is an instance of the Book object prototype.

Defining an object prototype

Define a constructor function with the object prototype's properties and functions:

function Book(title, author, numPages) {
	this.title = title;
	this.author = author;
	this.numPages = numPages;
	this.currentPage = 0;
	this.read = function() {
		this.currentPage = this.numPages;
		console.log("You read " + this.numPages + " pages!");
	};
}

Conventionally, object prototype names are capitalized.

http://bit.ly/intermediate-js-book

Instantiating an object

Now that we have a prototype, we can instantiate a new object:

var kindred = new Book('Kindred', "Octavia Butler", 211);

kindred.read(); // Will log "You read 264 pages!" to the console

This creates a new object that inherits the properties and functions from the prototype that we defined.

via GIPHY

What does new do?

  1. Creates a new Object
  2. Creates and binds a new this to that object
  3. Sets the new Object's prototype property to be the constructor function's prototype object
  4. Executes the constructor function
  5. Returns the newly created object

Adding new properties to objects

Let's say we've created two book objects using the Book prototype we set up earlier:

var persepolis = new Book('Persepolis', 'Marjane Satrapi', 160);

var frankenstein = new Book('Frankenstein', 'Mary Shelley', 280);

Let's add a series property to the first book:

persepolis.series = 'Persepolis';

This new property gets added to Persepolis, but not to Frankenstein, and not to any other new objects created from the Book prototype.

Adding new properties and functions to object prototypes

We can use the prototype property to add new properties and functions to the object prototype:

Adding a property:

Book.prototype.series = '';

Adding a function:

Book.prototype.buy = function(){
	console.log('You bought ' + this.name);
}

Let's Develop It!

Let's use our Book prototype, but let's add a couple of new properties and functions

  • rating - a number, rating out of 10
  • genre - a string, the genre of the book
  • getRating() - a function that logs a string to the console, e.g. "You rated this book x out of 10!"

 

Then instantiate a new Book object and call your new functions on it.

Object-oriented programming

Object prototypes can inherit properties and functions from other object prototypes.

Book

  • title
  • author
  • pages
  • read()

Ebook

Inherits from book, but also has:

  • filesize
  • download()

Paperback

Inherits from book, but also has:

  • cover
  • burn()

Extending object prototypes

First, define a constructor function

function PaperBack(title, author, numPages, cover) {
	Book.call(this, title, author, numPages);
	this.cover = cover;
}

Extend the Book object prototype

PaperBack.prototype = Object.create(Book.prototype);

Define a new function on this object prototype

PaperBack.prototype.burn = function() {
	console.log("Omg, you burnt all " + this.numPages + " pages");
	this.numPages = 0;
}

Instantiate a new object

var paperback = new PaperBack("1984", "George Orwell", 250, "cover.jpg");
paperback.read();
paperback.burn();

Inheritance

All Ebooks are Books, but not all Books are Ebooks.

Let's Develop It!

Building on the exercise from last time, create a new object prototype Hardcover that extends Book. The constructor should also take in an edition property.

Instantiate a new Hardcover object and call the read() function on it.

Add a new function to the Hardcover object prototype called getEdition() that logs a message to the console, e.g. "Your book is a first edition!"

Clearer Constructors

By passing in a config object, we can make our code easier to read and understand:

function Book(config) {
	this.title = config.title;
	this.author = config.author;
	this.numPages = config.numPages;
	this.currentPage = 0;
}

Then we pass in an object instead of a series of arguments to instantiate a new object:

var book = new Book({
	title: "Middlemarch",
	author: "George Eliot",
	numPages: 736
});

Optional Arguments

Use the || operator to define a default value for properties.

function Book(config) {
	this.title = config.title || "Untitled";
	this.author = config.author || "Unknown";
	this.numPages = config.numPages || 100;
	this.currentPage = 0;
}

var book = new Book({
	title: "In the Woods",
	numPages: 464
});

Let's Develop It!

Building on the exercise from last time, comment out the Hardcover code.

Change the Book constructor function to accept an object literal instead of multiple arguments.

Define a default value for every property.

Finally, instantiate a new Book object and call the read() function on it.

Questions?

Any questions on object prototypes or inheritance?