Sample Video Frame

22: More Complex OOP

The code from Exercise 21 works, but you'd be missing out on quite a few features of JavaScript OOP, and you don't receive any computation benefits. The JavaScript virtual machine will take advantage of your classes and potentially give you additional checks, potential optimizations, and other features. If you use your hand rolled "baby OOP" then you won't get any of these benefits.

This exercise is a video based exercise as it's much easier to see how these classes and objects work live. You'll enter in two code files and I'll walk through them in the video.

The Code

For this exercise you have two files to look at. First there's the code from the previous exercise but cleaned up so that you can compare it to the same code for this exercise:

const Person = (name, age, eyes) => {
    let obj = {
        name: name,
        age: age,
        eyes: eyes
    }

    obj.talk = (words) => {
        console.log(`I am ${obj.name} and ${words}.`);
    }

    return obj;
}

let alex = Person("Alex", 16, "green");
let mary = Person("Mary", 44, "brown");
let frank = Person("Frank", 34, "blue");

frank.talk("I am talking here!");
mary.talk("these are some words");
alex.talk("Hi there!");

console.log(`Frank is ${frank.age}, Mary is ${mary.age}, Alex is ${alex.age}`);

Now here's the new code but using the JavaScript (ES6) style of classes and objects:

class Person {
  constructor (name, age, eyes) {
    this.name = name;
    this.age = age;
    this.eyes = eyes;
  }

  talk(words) {
    console.log(`I am ${this.name} and ${words}.`);
  }
}

let alex = new Person("Alex", 16, "green");
let mary = new Person("Mary", 44, "brown");
let frank = new Person("Frank", 34, "blue");

frank.talk("I am talking here!");
mary.talk("these are some words");
alex.talk("Hi there!");

console.log(`Frank is ${frank.age}, Mary is ${mary.age}, Alex is ${alex.age}`);

You'll see that the code is very similar between the two files. In the video for this exercise I go through each line and compare the two so you can understand how they map.

What You Should See

When you run either of these files you shold get the same output:

$ node "code.js" 
I am Frank and I am talking here!.
I am Mary and these are some words.
I am Alex and Hi there!.
Frank is 34, Mary is 44, Alex is 16

Learn JavaScript Today

Register today for the Early Access course and get the all currently available videos and lessons, plus all future modules for no extra charge.


Still Not Sure? Try the next FREE Lesson!