Small Introduction to es6 classes…

A tiny look into extend and super.

If you’re a javascript programmer you’ve heard the term pseudoclassical inheritance, and you’ve seen something similar to these lines of code before when dealing with classes and subclasses…

var Grub = function(age, color) {
this.age = age;
this.color = color;
this.move = 0;
};
Grub.prototype.crawl = function () {
return this.move++;
};
var Bee = function(age, color) {
Grub.call(this, age, color);
this.job = 'Scare humans!';
};
Bee.prototype.fly = function () {
return this.move += 5;
};
//Here is where most people get lost.
Bee.prototype = Object.create(Grub.prototype);
Bee.prototype.constructor = Bee;

What if I told you there was an easier way!

In es6(ECMAScript 6) they finally make use of the word class in javascript, and given a much easier way to inherit methods from other classes. I’m going to show you how to do what was done in the example above, but in a much easier and clearer way using class. First let’s create our main class Grub again…

class Grub {
constructor (age, color) {
this.age = age;
this.color = color;
this.move = 0;
}
crawl() {
return this.move++;
}
}

Notice how all the methods go outside the constructor object. They don’t need to be assigned with dot or bracket notation. There isn’t even a need to attach function, just parameters and the body. The Grub parameters now go into the constructor parameters, and all of the ‘this’ made in the constructor object. This may seem confusing at first, but the next part makes it all worth it.

class Bee extends Grub {
constructor (age, color) {
super(age, color);
this.job = 'Scare humans!';
}
fly() {
return this.move += 5;
}
}

See no more Bee.prototype.fly or Bee.constructor, just simply add extends, and super to the constructor object. Extends tell’s super what to use in the constructor object, and you’ll get all the methods from that class while keeping it’s own methods.


One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.