Introduction

Classes in JavaScript are just a different way of representing constructor functions and methods from “prototype objects”, but without fundamentally changing the inheritance mechanism itself. Background class inheritance is the well-known mechanism of “method delegation” through the “prototype chain of inheritance”.
In JavaScript, the reserved word “class” only indicates that the query is a special type of function, which, unlike a regular function, cannot be called (invoke), but can only be used with the reserved word “new”.
This functionality was introduced into the language with the ES2015 standard, with the intention of improving readability and facilitating the writing of object-oriented programs. When defining the appearance of the syntax, the designers of the standard were guided by the idea of creating such a syntax that will resemble the syntax of most “class” languages”, and thus help programmers who already program in a “class” language” to more easily adopt the JavaScript syntax.
If in the following examples we compare parts of the code written with different syntaxes, we can see that the class syntax is better readable compared to the ES5 syntax:
Example: ES5 syntax
|
1 2 3 4 5 6 7 8 9 |
var Osoba = (function () { function Osoba(ime) { this.ime = ime; } Osoba.prototype.objavi = function () { console.log("This is it" + this.ime); }; return Osoba; })(); |
Example: Class Syntax
The layout of the class is very similar to the object creation syntax according to the ES5 standard, although it is more readable due to fewer lines and unnecessary parts removed:
|
1 2 3 4 5 6 7 8 |
class Osoba{ constructor(ime) { this.ime = ime; } objavi() { console.log("This is it" + this.ime); } } |
NOTE:
Unlike other “class languages”, creating objects in Javascript (even when using classes) is not static ie. is not immutable after the object‘s declaration. In JavaScript, an object after instantiation remains “bound” to the class, with its “prototype object” through the chain of inheritance. Therefore, if we subsequently add or change a method in the class itself, that change will be felt by every object instantiated on the basis of that class.


