OOP AND PROTOTYPE IN JAVASCRIPT

JS

Object-oriented programming Is a paradigm that focuses on objects instead of functions. Let’s look at the image below.

Paradigma OOP

WHAT ARE THE OBJECTS?

Objects are data structures that integrate variables and functions within them. Variables are called properties and functions are called methods. The four pillars of OOP are shown in the image opposite.

OOP

ENCAPSULATION

To encapsulate means to enclose in a capsule. Related data and functions are grouped together. The functions or methods work internally with the data to perform the required operations.

Incapsulamento

ASTRACTION

The concept of abstraction is based on the “what.” the goal of abstraction is to expose the essentials and hide the complexities. Take a DVD player as an example, such an electronic device exposes a user interface consisting of the start, stop, pause etc. buttons. But it hides the hardware complexities behind it.

Astrazione

INHERITANCE

Through inheritance, an object can access properties and methods of another object avoiding duplication of code.

ereditarietà

POLYMORPHISM

Polymorphism literally means having many forms. A same method named m can have different behaviors depending on the context in which it operates.

Polimorfismo

I briefly summarize with the image below.

OOP

ACCESS TO THE PROPERTIES OF AN OBJECT

As we know to access object properties we use dot notations, objectname.propertyname. Let us look at the code below to clarify the concept.

Copy to Clipboard

LITERAL OBJECT TO CONSTRUCTION FUNCTION

Sometimes to avoid unnecessary duplication of code you can use what are called factory functions or rather constructor functions. Look at the code given below.

Copy to Clipboard

HIDE DETAILS AND EXPOSE ONLY THE ESSENTIALS

We see how in JS one can simply implement one of the four pillars of OOP, the abstraction. Code below.

Copy to Clipboard

PROTOTYPE CHAIN

The mechanism in JS of inheritance is implemented through the prototype chain. Through it an object can access properties and methods of another object. With this mechanism we avoid duplication of code, obj2 and obj3 don’t need to define the method fn1() unless they need to redefine it. Look at the two figures below.

Prototipi
Prototipi

CODE EXAMPLE

Let’s look at an example on a prototype chain.

Copy to Clipboard

CHAIN OF PROTOTYPES REPORTED IN THE CODE

Catena dei prototipi

THE __PROTO__ PROPERTY

Using __proto__ on an object we can trace back to its prototype. By adding a whole series of instructions __proto__ we can move up the prototype chain. It is deprecated, to know the prototype of an object use getPrototypeOf().

SAMPLE CODE

Copy to Clipboard

SETPROTOTYPEOF AND GETPROTOTYPEOF

With Object.setPrototypeOf(object1,object2); you set the prototype of an object. Instead Object.getPrototypeOf(object) returns the prototype of the object passed in input.
Copy to Clipboard

THE KEYWORD THIS


this is the reference to the current execution contex
,which is the object in which we are operating. The first thing the JS engine does before the execution of the first line of code is to create a global execution context i.e., a global object in which all our code is executed, and it causes this be a reference to this global object (window). The value of this within a function depends on how it is invoked.

Copy to Clipboard

EXPLICIT BINDING WITH BIND, CALL, AND APPLY

Through explicit binding, it is possible to make this refer to a certain object. Call and Apply work almost the same way, on the other hand Bind takes as input the object to which this it needs to refer to and resituates a reference to the function.

Copy to Clipboard

THIS AND ARROW FUNCTION

If we have a function that needs to work with the properties of an object we use the classical syntax, otherwise arrow functions.
Copy to Clipboard

ITERATE AN OBJECT

Normally, a loop is used for in to cycle through an object’s properties, keys, and values. Such a cycle is capable of moving up the prototype chain. Instead if we want to iterate only the object excluding prototypes we use the method hasOwnProperty().
Copy to Clipboard

OBJECT DEFINEPROPERTY

If we want to add a new property to an object, we define its characteristics, and use the method Object.defineProperty(…).

Copy to Clipboard

OBJECT PREVENTEXTENSIONS

The code below explains this JS method.

Copy to Clipboard

DEEPENING AI

In JavaScript, the prototype is a mechanism that allows objects to inherit properties and methods from other objects. Every object in JavaScript has a reference to a prototype object from which it inherits features. This reference is found in the hidden property [[Prototype]], which is accessed via Object.getPrototypeOf() or the less common notation __proto__.

Prototype construction

When you create an object or function constructor in JavaScript, the latter has a property called prototype, which defines the properties and methods that all objects created via that constructor will inherit. For example:

function Persona(nome, età) {
       this.nome = nome;
       this.età = età;
}

Persona.prototype.saluta = function() {
       console.log(`Ciao, mi chiamo ${this.nome}`);
};

let persona1 = new Persona(‘Mario‘, 30);
persona1.saluta(); // “Ciao, mi chiamo Mario”

In this example, Persona.prototype is the prototype of persona1, which means that persona1 inherits the saluta() method.

Chain of prototypes

The concept of “prototype chain” (or Prototype Chain) refers to the fact that an object can inherit properties not only directly from its prototype, but also from its prototypes’ prototypes, thus creating a chain of inheritance.

When an object’s property or method is accessed, JavaScript first checks to see if it exists on that object. If it doesn’t find it, it goes looking in its prototype, then in the prototype of the prototype, and so on, until it reaches the Object.prototype object, which is the progenitor of all objects in JavaScript.

console.log(persona1.toString()); // Viene chiamato Object.prototype.toString()

In this example, persona1 has no toString() method, so JavaScript searches the prototype chain until it finds Object.prototype.toString().

Methods call(), apply() and bind()

call()

The call() method allows you to invoke a function by specifying the value of this and the arguments individually. This is useful when you want to use a function in a different context by associating it with another object.

function saluta() {
     console.log(`Ciao, mi chiamo ${this.nome}`);
}

let persona2 = { nome: ‘Anna‘ };
saluta.call(persona2); // “Ciao, mi chiamo Anna”

In this example, the call() method sets the this context of the saluta function to persona2.

apply()

The apply() method is similar to call(), but instead of passing the arguments individually, you pass an array of arguments.

function somma(a, b) {
       console.log(a + b);
}

somma.apply(null, [2, 3]); // 5

Here, apply() accepts an array of arguments and passes them to the somma function.

bind()

The bind() method creates a new function with the same body and scope as the original function, but with the value of this fixed to a given object. It is useful when you want to bind a function to a particular context and use it later.

function saluta() {
     console.log(`Ciao, mi chiamo ${this.nome}`);
}

let persona3 = { nome: ‘Marco‘ };
let salutaMarco = saluta.bind(persona3);
salutaMarco(); // “Ciao, mi chiamo Marco”

Unlike call() and apply(), bind() does not immediately invoke the function, but returns a new function with the context this bound.

Differences between call(), apply() and bind().

-call(): invokes the function immediately and allows arguments to be passed one by one.

-apply(): immediately invokes the function but the arguments are passed in an array.

-bind(): does not immediately invoke the function, but returns a new function with the this set.

Conclusion

The concepts of prototype and prototype chain are fundamental to understanding how inheritance works in JavaScript. The call(), apply() and bind() methods allow flexible handling of the this context, allowing functions with different contexts to be reused or bound permanently.

LINKS TO PREVIOUS POSTS

THE JAVASCRIPT LANGUAGE

LINK TO CODE ON GITHUB

GITHUB