Constructor Functions & OOP

Daily Standup

Continuing the course today…today was all about object oriented programming in JavaScript.

Constructor Functions

Today we reviewed constructor functions using the keyword new. One thing that was new to me was how you can DRY up code by using the call or apply methods to create a constructor from another:

function Car(make, model, year){
this.make = make;
this.model = model;
this.year = year;
this.numWheels = 4;

// Make a new function using call
function Motorcycle(make, model, year){, make, model, year)
this.numWheels = 2;

// Or put the arguments in an array with apply
function Motorcycle(make, model, year){
Car.apply(this, [make,model,year]);
this.numWheels = 2;

// Or use apply with the arguments keyword!
function Motorcycle(){
Car.apply(this, arguments);
this.numWheels = 2;

Or actually I thought it was new but then found it in my notes from several months ago 😂. So a necessary review apparently!

Prototypal Inheritance

One thing that actually was new was learning about prototypal inheritance, which is how you can create a new object based on another object, including methods that are attached to the original object’s prototype. There are two steps:

  1. Create the object.
  2. Reset the constructor property to transfer this to the new object:
// Original object constructor
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;

// Add a method to its prototype
Person.prototype.sayHi = function(){
return "Hello " + this.firstName + " " + this.lastName;

// New object constructor based on the first
function Student(firstName, lastName){
return Person.apply(this, arguments);

// Theoretically this is how you would add a method to the new Constructor
// WRONG! This will also mutate the original object's prototype
Student.prototype.sayHi = function(){
return "Hello " + this.firstName + " " + this.lastName;

// Instead you can create a new object which inherits its prototype
// STEP ONE - create object
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor; // Person

//STEP TWO - reset constructor
Student.prototype.constructor = Student;

Other Stuff

Now we’re learning how to build a JSON API…today we set up the basic structure and will build from there.

Up Next

Finish building a JSON API then the next module is ES6 (FINALLY!!!!).

I also started on a new web project with CSS Grid which is fun! I want to finish it in the next couple of weeks.

Also trying to read the book Clean Code…I have it one more week at the library so need to find the time to read that too lolz…