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.

Future versions of JavaScript are already in the works with more OO features built into the language.

JavaScript Object Prototypes

Every object in JavaScript has a prototype.

All JavaScript objects inherit their properties and their methods 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() method
  • It will have a filter() method
  • It will have a join() method

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

Object Prototype Example

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

Book prototype

Properties:

  • title
  • author
  • pages

Methods:

  • read()
  • buy()

Object Prototype Instances

There can be many instances of object prototypes:

The Giver

by Lois Lowry

179 pages

Fox in Sox

by Dr. Seuss

62 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 methods:

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.

Instantiating an object

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

var book = new Book("Robot Dreams", "Isaac Asimov", 320);

book.read(); // Will log "You read 320 pages!" to the console

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

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 myBook1 = new Book('The Boxcar Children', 'Gertrude Chandler Warner', 160);

var myBook2 = new Book('Around the World in 80 Days', 'Jules Verne', 315);

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

myBook1.series = 'The Boxcar Children';

This new property gets added to The Boxcar Children, but not to Around the World in 80 days, and not to any other new objects created from the Book prototype.

Adding new properties and methods to object prototypes

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

Adding a property:

Book.prototype.series = '';

Adding a method:

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

Let's Develop It!

Create a Video object prototype. The Video object prototype should have the following properties and methods:

  • title - a string
  • uploader - a string, the person who uploaded the video
  • seconds - a number, the duration of the video
  • watch() - a method that logs a string to the console, e.g. "You watched all 76 seconds of Maru in a box!"

 

Then instantiate a new Video object and call the watch() method on it.

Object-oriented programming

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

Book

  • title
  • author
  • pages
  • read()
  • buy()

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 method 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 MusicVideo that extends Video. The constructor should also take in an artist property.

Instantiate a new MusicVideo object and call the watch() method on it.

Add a new method to the MusicVideo object prototype called rockOut() that logs a message to the console, e.g. "You just rocked out to Shake it Off by Taylor Swift!"

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: "Robot Dreams",
	author: "Isaac Asimov",
	numPages: 320
});

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: "Robot Dreams",
	numPages: 320
});

Let's Develop It!

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

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

Define a default value for every property.

Finally, instantiate a new Video object and call the watch() method on it.

Questions?

Any questions on object prototypes or inheritance?