Finishing OOP JavaScript at Treehouse

2 min read

\"OOP

We learned a bit about constructors and prototypal inheritance in OOP JavaScript in this final section. We also went over prototype chaining which I found interesting.

Inheritance of Properties Through the Prototype Chain

Every JavaScript object has a Prototype object and inherit from Object.prototype. You cannot inherit from classes in JavaScript as there is no “class” per se. You only inherit from other objects.

In order to spread functionality throughout different functions and scopes, we can chain different objects together using the inherent nature of Object.prototype. We can do this a couple of ways but in the Treehouse example, we use Object.create() to chain together two objects.

Take for example this code:

function Media() {

  this.title = title;

  this.duration = duration;

  this.isPlaying = false;

}

Media.prototype.play = function() {

  this.isPlaying = true;

};

Media.prototype.stop = function() {

  this.isPlaying = false;

};

This is an example of a constructor with some functionality. What if I have another constructor that I want to inherit properties from this constructor? You could do this:

function Movie() {

  Media.call(this, title, duration);

  this.year = year;

}

Movie.prototype = Object.create(Media.prototype);

Movie.prototype.stop = function() {

  this.isPlaying = false;

};

The Movie() constructor is inheriting properties from the Media() constructor.

The call() Method

You can also use call() to chain constructors for an object. In the example above, we’ve used:

function Movie() {

  Media.call(this, title, duration);

  this.year = year;

}

The call() method always takes two or more arguments, with this always being the first, which refers to the current object, or the calling object.

The Final Project for OOP JavaScript at Treehouse

I was lost. I honestly don’t know how I was supposed to come up with the answers provided. I didn’t know where to start, which was honestly my fault. I didn’t take very good notes while going through the course at the end. But I wasn’t the only one stumped by this challenge. I don’t feel I was prepared enough for it, regardless of how many notes I took. You can find the gist of the solution down below.

See what I mean? We didn’t learn half this stuff. I love Treehouse and this was a hard course for Andrew to teach. But I felt it sorely lacking in practice.

CC BY-SA 4.0 Finishing OOP JavaScript at Treehouse by Tiffany White is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.