Are Javascript Classes really Classes?
Finally! ECMAScript has finally brought classes to the JS language. Right?
NOPE!
MDN describes classes like this -
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
So what is a Classes purpose if it doesn’t introduce a new object-oriented inheritance model to Javascript? Through the grapevine I heard it was included inside ECMAScript 2015 to help acclimate developers who were transitioning from other Class based programming languages.
I don’t know if that’s true, but JS Class is a great way to organize our code inside one block. Instead of having to separate our constructor and methods, from each other like we do with typical prototypal inheritance, we can include our constructor and methods all within one code block. Let’s take a look at an example.
The Class structure is great. Initially we use the special constructor
method to initialize our created object. Then still within our class Car
we were able to define two separate methods, a makeAndModel
and horsepower
method. In my humble opinion a much better way then writing -
Both accomplish the exact same thing. But what’s nice with Class is our methods are defined right there inside our Class code block. JS Class also gives you the ability for one Class to be the child of another Class. So the child Class is basically inheriting from the parent Class. But inside that child Class you can redefine other methods defined inside the parent. Let’s take a look at a bad example but example non the less -
As you can see we created a new class Mitsubishi
that is a child of the parent class Car
. But also inside Mitsubishi we redefined the makeAndModel
method. Pretty simple right. MDN describes more about classes and all of it’s ins and outs. Caution be careful of using extends
and redefining methods. It can get out of hand quickly.
That’s it for this blog. I’m off to the next project and topic.