CLASS DEFINITION

In object-oriented programming, a class is a construct of a programming language used as a model for creating objects. The model  JS includes attributes and methods that will be shared by all objects created (instances) from the class. An “object” is, in fact, the instance of a class. In modern JavaScript there is a more advanced “class” construct, which introduces very useful new possibilities for object-oriented programming.

THE SYNTAX OF CLASS

class MyClass {

  // metodi della classe

  constructor() { … }

  method1() { … }

  method2() { … }

  method3() { … }

  …

}

new MyClass() will create a new object with all methods in the class. The constructor() method is called automatically by new, so we can use it to initialize the object.

For example:

class User {

  constructor(name) {

    this.name = name;

  }

  sayHi() {

    alert(this.name);

  }

}

// Utilizzo:

let user = new User(“John”);

user.sayHi();

When called new User(“John”):

  1. A new object is created;
  2. The constructor () method is called and assigns the given argument to this.name.… Now we can call the methods, for example user.sayHi.

    WHAT IS A CLASS

    So, what exactly is a class? Contrary to what one might think, this is not a completely new concept. So let’s see what a class actually is. This will help us understand more complex aspects. In JavaScript, a class is a kind of function.

    Observe:

class User {

  constructor(name) { this.name = name; }

  sayHi() { alert(this.name); }

}

// prova: User è una funzione

alert(typeof User); // function

The construct class User {…} therefore:

  1. Create a function called User, which becomes the result of the class declaration. The instructions of the function come from the constructor method (considered empty if not present);
  2. Save all methods (like sayHi) inside User.prototype.

When we call a method from an object, it will be taken from the prototype. Thus, a new User object has access to the methods of the class.

We can represent the result of the User class declaration as:

Classes javascript

The following code will allow you to analyze it:

class User {

  constructor(name) { this.name = name; }

  sayHi() { alert(this.name); }

}

// una classe è una funzione

alert(typeof User); // function

// …o, più precisamente, il costruttore

alert(User === User.prototype.constructor); // true

// I metodi sono in User.prototype:

alert(User.prototype.sayHi); // il codice del metodo sayHi

// ci sono due funzioni all’interno del prototipo

alert(Object.getOwnPropertyNames(User.prototype)); // constructor, sayHi

// la classe User usando solo funzioni

// 1. Costruttore

function User(name) {

  this.name = name;

}

// tutte le funzioni hanno un costruttore predefinito (di default)

// dunque non va creato

// 2. Aggiungiamo un metodo al prototipo

User.prototype.sayHi function() {

  alert(this.name);

};

// Utilizzo:

let user = new User(“John”);

user.sayHi();

The result of this code is about the same. It is therefore logical to think that class is only a syntax sugar. There are, however, some important differences. A function created through class is labeled with the special internal property [[IsClassConstructor]]: true. So it’s not exactly the same as creating it manually. Unlike a normal function, the constructor of a class can only be called via the new keyword:

class User {

  constructor() {}

}

alert(typeof User); // funzione

User(); // Errore: Il costruttore della classe può essere richiamato solo attraverso ‘new’

Also, in most JavaScript engines the constructor starts with “class”

class User {

  constructor() {}

}

alert(User); // class User { … }

  1. There are other differences, which we will discover later.
  2. Methods of classes are uncountable. The definition of a class sets the enumerable flag to false for all methods within the “prototype”.

This is good, as we don’t want to display methods when we use a for..in loop to display an object.

3. The contents of a class always run in strict.

In addition to these, the class syntax brings other features, which we will explore later.

THE CLASS EXPRESSION

Like functions, classes can be defined within another expression, passed as a parameter, returned, assigned, etc.

Here is a small example:

let User = class {

  sayHi() {

    alert(“Hello”);

  }

};

Similar to Named Function Expression, classes may or may not have a name. If a class has a name, it is visible only within the class:

// “Named Class Expression”

let User class MyClass {

  sayHi() {

    alert(MyClass); // MyClass è visibile solo all’interno della classe

  }

};

new User().sayHi()// funziona, restituisce la definizione di MyClass

alert(MyClass); // errore, MyClass non è visibile al di fuori della classe

GETTER AND SETTER 

As with literal objects, classes can include getters/ setters, generators, properties, etc.

The following example implements user.name through get/set:

class User {

constructor(name) {

// invoca il setter

this.name = name;

}

get name() {

return this._name;

}

set name(value) {

if (value.length < 4) {

alert(“Name is too short.”);

return;

}

this._name value;

}

}

let user = new User(“John”);

alert(user.name); // John

user = new User(“”); // Nome troppo corto.

In the examples above, the User class contained only methods. Let’s add a property:

class User {

name “Mario Rossi”;

sayHi() {

alert(`Hello, ${this.name}!`);

}

}

new User().sayHi();

So we just write “=” in the declaration. The important difference of the fields of a class is that they are set on the individual object and not on User.prototype:

class User {

name = “John”;

}

let user = new User();

alert(user.name); // John

alert(User.prototype.name); // undefined

Copy to Clipboard
Copy to Clipboard
Copy to Clipboard

DEEPENING AI

Classes in JavaScript are a way to define objects and their behaviors. Although JavaScript is not a pure object-oriented language (like Java or C++), with the introduction of ECMAScript 6 (ES6), classes were added to facilitate the creation of objects and to provide a more familiar syntax for developers coming from object-oriented languages.

What is a class?

A class in JavaScript is essentially a pattern or model for creating objects. It defines the properties and methods that objects created from it will have. It is a way of defining objects in a more structured way, while retaining the same functionality that could be achieved by using constructor functions and prototypes (prior to ES6).

Defining a class

Here is a basic example of a class in JavaScript:

class Persona {
     constructor(nome, eta) {
        this.nome = nome;
        this.eta = eta;
     }

     descrizione() {
        return `${this.nome} ha ${this.eta} anni.`;
     }
}

const persona1 = new Persona(“Mario“, 30);
console.log(persona1.descrizione()); // “Mario ha 30 anni.”

Example breakdown:

1. Class definition: The Persona class is defined using the class keyword. It is like a template for creating objects that will have nome and età.

2. Constructor: The constructor method is executed when creating a new instance of the class (with new). In this case, it accepts two parameters, nome and età, and assigns them to the properties of the object.

3. Method: The Persona class has a method called descrizione, which returns a string with the person’s nome and età. This method will be available on all instances of the class.

Constructor (constructor).

The constructor is a special method for initializing properties of the object. It can accept parameters that are used to set property values.

class Auto {
         constructor(modello, anno) {
            this.modello = modello;
            this.anno = anno;
}
}

In this case, when creating a new Auto, you can pass the modello and anno that will be stored as properties of the object.

const auto1 = new Auto(“Fiat“, 2021);
console.log(auto1.modello); // “Fiat”
console.log(auto1.anno); // 2021

Methods

Classes can have methods to define behaviors. As already seen, the descrizione method in Persona is an example. Methods within classes do not require the function keyword.

class Cerchio {
     constructor(raggio) {
        this.raggio = raggio;
     }

     // Metodo per calcolare l’area del cerchio
     area() {
         return Math.PI * this.raggio * this.raggio;
     }
}

const cerchio1 = new Cerchio(5);
console.log(cerchio1.area()); // 78.53981633974483

Static Properties and Static Methods

Static properties and static methods belong to the class itself, not to individual instances. This means that they cannot be invoked on an instance of the class, but only on the class directly.

Example of a static method:

class Matematica {
      static somma(a, b) {
          return a + b;
      }
}

console.log(Matematica.somma(2, 3)); // 5

In this example, the somma method can be called directly on the Matematica class, without creating an instance of it.

Inheritance (Inheritance).

JavaScript also supports inheritance between classes. The extends keyword allows you to create a new class based on an existing class.

Here is an example of inheritance:

class Animale {
     constructor(nome) {
           this.nome = nome;
      }

      parla() {
           console.log(`${this.nome} fa un suono.`);
      }
}

class Cane extends Animale {
       parla() {
             console.log(`${this.nome} abbaia.`);
       }
}

const cane = new Cane(“Fido“);
cane.parla(); // “Fido abbaia.”

Example breakdown:

1. Base class (superclass): The Animale class is a generic class with a constructor that accepts a name and a parla method that outputs a generic message.

2. Derived class (subclass): The Cane class extends Animale using the extends keyword. However, it redefines (or overrides) the parla method to provide dog-specific behavior.

3. super: When a subclass wants to access the constructor of its superclass, it can use the super keyword. It is generally used in the constructor of the subclass to call the constructor of the superclass.

class Gatto extends Animale {
       constructor(nome, razza) {
          super(nome); // chiama il costruttore della classe genitore (Animale)
          this.razza = razza;
       }

       parla() {
           console.log(`${this.nome} miagola.`);
       }
}

const gatto = new Gatto(“Whiskers“, “Siamese“);
gatto.parla(); // “Whiskers miagola.”

In this example, super(name) is called in the Gatto constructor to initialize the name property of the base class Animal.

Getters and Setters

Classes can also have getters and setters, which allow you to define methods that act as properties.

class Rettangolo {
       constructor(lunghezza, larghezza) {
         this.lunghezza = lunghezza;
         this.larghezza = larghezza;
       }

       // Getter per l’area
       get area() {
           return this.lunghezza * this.larghezza;
       }

        // Setter per modificare la lunghezza
        set nuovaLunghezza(valore) {
              this.lunghezza = valore;
       }
}

const rettangolo = new Rettangolo(10, 5);
console.log(rettangolo.area); // 50 (usa il getter)
rettangolo.nuovaLunghezza = 20; // usa il setter
console.log(rettangolo.area); // 100

In this example, the area of the rettangolo is calculated using a getter, while the length can be changed using a setter.

Anonymous classes and class expressions

You can define an anonymous class or use a class expression, that is, a class that has no name or is defined within an expression:

let Utente = class {
       constructor(nome) {
         this.nome = nome;
       }

      saluta() {
         console.log(`Ciao ${this.nome}`);
      }
};

const utente = new Utente(“Luigi“);
utente.saluta(); // “Ciao Luigi”

Summary

-Classes in JavaScript provide an easier and more organized way to create objects.

-The class keyword was introduced with ES6 to create models for objects.

-Constructor is a special method used to initialize object properties when a new instance is created.

-Methods defined in classes are functions associated with objects created by the class.

-Classes can inherit from other classes using extends, and superclass members can be accessed with super.

-Getters and setters provide a way to get or set values as if they were properties, but they are actually methods.

Classes in JavaScript represent an evolution of object management, introducing a more modern syntax and simplifying some operations compared to the traditional prototype-based approach.

THE JAVASCRIPT LANGUAGE

THE JAVASCRIPT LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB