Kevin Guebert

Kevin Guebert

☕️ Proudly built in Atlanta, GA

Simple Object Oriented Programming with Javascript

Thursday, July 5, 2018

2 min read

Constructing

With the introduction of ES6, creating classes in Javascript has improved. Even though the new syntax boils down to the same as it was previously done, coming from other OOP languages makes it easier to understand.

Previously, for creating classes before ES6 we would do it this way:

1function Pet(type, name) {
2 this.type = type;
3 this.name = name;
4}
5var winnie = new Pet("cat", "Winnie");

Now with ES6, we can use the class syntax:

1class Pet {
2 constructor(type, name) {
3 this.type = type;
4 this.name = name;
5 }
6}
7var toby = new Pet("dog", "Toby");

If you want to check and see whether these are the same, you can run a typeof on both of them and you will see that both are of type function!

Inheritance

Inheritance with Javascript works very similarly to other languages:

1class Pet {
2 constructor(name) {
3 this.name = name;
4 }
5 feed() {
6 console.log(`Feeding ${this.name}`);
7 }
8}
9
10class Cat extends Pet {
11 constructor(name) {
12 super(name);
13 console.log("Cat created");
14 }
15 meow() {
16 console.log("Meow!");
17 }
18}
19
20class Dog extends Pet {
21 constructor(name) {
22 super(name);
23 console.log("Dog Created");
24 }
25 bark() {
26 console.log("Woof!");
27 }
28}
29
30const winnie = new Cat("Winnie"); // Cat created
31const toby = new Dog("Toby"); // Dog created
32winnie.name; // "Winnie"
33toby.name; // "Toby"
34winnie.meow(); // "Meow!"
35winnie.bark(); // Uncaught TypeError: winnie.bark is not a function
36toby.bark(); // "Woof!"
37toby.meow(); // Uncaught TypeError: toby.meow is not a function
38winnie.feed(); // Feeding Winnie
39toby.feed(); // Feeding Toby

As you can see above, both Cat and Dog inherit the same feed() method, but they both have their own methods meow() and bark() that only those instances can reference!

Hope you enjoy this little JS snippet!