Classes in JavaScript and How to Use Them

Classes in JavaScript and How to Use Them

Classes in JavaScript are just a different way of presenting the constructor function and methods from “prototype objects“, but without essentially changing the inheritance mechanism itself. Background class inheritance is a known mechanism of “delegating methods” through the “prototype chain of inheritance“.

In JavaScript, the reserved word “class” merely indicates that the query is a special type of function, which, unlike an ordinary function, cannot be invoked but can only be used with the reserved word “new“.
This functionality has been introduced into the language with the ES2015 standard, with the intention of improving readability and facilitating the writing of object-oriented programs. In defining the appearance of syntax, the designers of the standard were guided by the idea of creating such syntax that would resemble the syntax of most “class” languages, and thus help programmers already programming in a “class” language to more easily adopt JavaScript syntax.
If we compare the parts of code written in different syntax in the following examples, we can see that the better readability of class syntax compared to ES5 syntax:

Example: ES5 syntax

var Person = (function () {
     function Person (name) {
         this.name= name;
     }
     Person.prototype.post = function () {
         console.log ("This is" + this.name);
     };
     return Person;
}) ();

Example: Class syntax

The layout of the class is very similar to the syntax for creating an object according to the ES5 standard, although it is more readable due to fewer lines and unnecessary parts thrown out:

class Person {
     constructor (name) {
         this.name= name;
     }
     publish () {
         console.log ("This is" + this.name);
     }
}

REMARK:
Unlike other “class languages”, creating objects in Javascript (even when using classes) is not static, ie it is not invariable after declaring an object. In JavaScript, the object remains instantiated after the instantiation by its class, its “prototype object” via the inheritance chain. Therefore, if we subsequently add or change a method in the class itself, that change will be felt by every object instantiated based on that class.

Basic characteristics

Creating classes

However, since classes are just functions, as with all functions, there are two ways to create them:

Function declarations
Here’s the most common way to write classes:

class nameClass {
    // BODY CLASS
}

The main difference between a function declaration and a class declaration is that the classes do not “hoist” when compiled to the beginning of the program code as a function. So it should be noted that the class is defined before using “new” to create a new object.

Function expressions
This approach is rarely used, but a completely legal way to create classes:

var nameClass = class {
   // BODY CLASS
}

As with ordinary function expressions, there is no hoist here.

REMARK:
The class body is executed in strict mode.

Methods

Basic methods
We define methods as functions, but without the keyword function. Although it should be noted that methods within the class have an “enumerable” property set to false, which means that no “for..in” loops are available at startup.

Constructor method
A constructor is a special method that creates and initializes an object. This method is a counterpart to the constructor function of ES5, defining everything needed to initialize a new object, noting that there can be only one “constructor” method within one class.

constructor {
   // BODY METHODS
}

Static methods
Static methods are methods that do not belong to the instantiated object but to the class itself, so they cannot be accessed from the instantiated object. The only approach to these methods is through the class itself. Such methods are defined using the reserved word “static” in front of the method name.

static Methodname {
   // BODY METHODS
}

Get and Set methods
In many programming languages, access to private properties is achieved using special methods. So is JavaScript, where such methods are denoted within a class by adding the reserved word “get/set” in front of the method name itself.

Example

class Heroj {
    constructor() {
        this._health = 100;
    }
    get publishStatus() {
        console.log("Health is " + this._health);
    }
    set pricedImpact(blow){
       if (this._health - blow> 0){
         this._health -= blow;
         this.publishStatus;
      } else {
        console.log("Hero is dead!");//
      }
    }
    set healtstatus(help){
      if (this._health + help>100){
        this._health = 100;
        this.publishStatus;
      } else {
        this._health += help;
        this.publishStatus;
      }
    }
}
 
var batman = new Hero();
batman.publishStatus           // Returns: "Health is 100"
batman.pricedImpact=50;     // Returns: "Health is 50"
batman.healtstatus=20;       // Returns: "Health is 70"
batman.pricedImpact=80;     // Returns: "The hero is dead!"

REMARK:
Get / Set methods are defined within a class as a method but are accessed in the same way as if they were object properties.
a) This method is accessed within another method as if it were a normal property of an object:

this.publishStatus

b) The Get method is also called in the newly generated object as an object property:

batman.publishStatus

c) Even the “set” method is approached as assigning value to the ordinary property of an object:

batman.healtstatus=20;

Inheriting classes

Syntax
Class inheritance requires the extends keyword and the name of the object to be inherited in the class declaration itself. Declaration in the following example The heir extends The parent “tells” us that the Heir.prototype object has been linked to the Parent.prototype object.

class Heir extends Parent {
    // BODY CLASS
}

When creating a new class that inherits another class, we must make sure that the constructor function of the parent class is called when defining the construction functions. Reserve the word super points to the parent constructor function, and uses the “super ()” method to call the base class constructor. This call to the base class constructor must be made at the very beginning of the construction functions! (because it defines the keyword “this.”)
However, if it does not explain the “super ()” methods in our constructor functions, JavaScript will run the error: “It must invoke the super constructor in the derived class before accessing ‘this’ or returning from the derived constructor.” It will publish an error even if it does not use “this” in our constructor, as in the following case:

class Person {
     constructor () {
        console.log ("I'm a person.")
     }
}
class Developer extends Person {
    constructor () {
        console.log ("I'm a Developer!")
     }
}
 
var alen = new Programmer (); // Returns Error: "Must call super constructor in derived class before accessing 'this' or returning from derived constructor"

So if in the new class we have a constructor method (even if it is empty) “we have to call the super () method”!

EXPLANATION:
Calling the super () method executes all the code from the basic constructor function and defines that this points to newly-generated objects.

class Person {
     constructor () {
        console.log ("I'm a person.")
     }
}
class Developer extends Person {
     constructor () {
       super();
       console.log ("I'm a Developer!")
    }
}
 
var alen= new Programmer (); // Returns: "I'm a person."
                                   // Returns: "I'm a Programmer!"

What happens if the new class does not have a constructor () method defined?

class Person {
     constructor () {
        console.log ("I'm a person!")
     }
}
class Developer extends Person {
 
}
 
var alen = new Programmer (); // "I'm a person!"

In this case, JavaScript builds its internal (hidden) constructor function for us, which looks like this:

constructor (...args){
  super(...args);
}

Access to the base class property

We access the base class property as standard with “this.property”:

class Person {
     constructor (name) {
       this._ime = name;
     }
}
class Developer extends Person {
     constructor (name) {
       super (name);
       console.log (this._ime + "is a developer!")
    }
}
 
var alen = new Programmer ("Alen"); // Returns "Dear Developer!"

Access to the base class method

The reserved word super represents a “parent” constructor, so when we need access to a base class method, we approach it with a “super.methodname”:

class Person {
     constructor (name) {
         this._name = name;
         console.log ("My name is defined in the base class.");
     }
     showName () {
         console.log ("I am" + this._name);
     }
}
 
class Developer extends Person {
     constructor (name, programming language) {
         super (name);
         this.programming language = programming language;
     }
     showLanguage() {
         super.showName ();
         console.log (this._name + 'use' + this.programmingLanguage + '.');
     }
}
 
var alen = new Programmer ('Alen', 'JavaScript');
alen.showLanguage(); // "My name is defined in the base class."
                            // Returns: "I'm Alen"
                            // Returns: 'The dragon uses JavaScript.'
Likes:
15 0
Views:
1665
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

Your email address will not be published. Required fields are marked *