What is the Javascript Prototype?

Hi, we have heard that Javascript is based in Prototypes, but what is a Prototype?

Javascript is an object-oriented programming language and it structure is based in Prototypes, this is the reason why the object it is the main abstraction.

A Prototype is a delegation object that is used to implement inheritance based in prototypes.

If the prototype is not explicitly set,  then the objects receive a default prototype.

All the objects (all the things in JS are objects) in Javascript inherit from this main object:

Object.prototype

And this main Object (Object.prototype)  always will be the last object from which all objects inherit.

how does this main Object works?

“If a property is not found in the object itself, there is an attempt to search the prototype, but it wasn’t found, then the prototype of the prototype is searched, until all the prototype chains are exhausted, this is known as delegation.” 

If the final prototype is null; this will mean that the current prototype is the last one.

Let’s see an example to clarify this definition:

I have this object called myData that have 2 properties and one method.

let myData = {
  name: 'Cristina',
  age: 31,
  sayHello: () => {
    console.log('Hi!');
  }
}

Then I have the next code with “__proto__” that is automatically added to every object by Javascript motor engines.

let myData = {
  name: 'Cristina',
  age: 31,
  sayHello: () => {
    console.log('Hi!');
  }
}

myData.__proto__.sayHello = () => {
  console.log('Hi From myData._proto_.sayHello!');
}

Again with __proto__ I can add the same name of the method called “sayHello“.

So the methodsayHello” is added in myData object and its prototype (myData.__proto__)

If I executed the “sayHello” method, I will have as a result ‘Hi!’

let myData = {
  name: 'Cristina',
  age: 31,
  sayHello: () => {
    console.log('Hi!');
  }
}

myData.__proto__.sayHello = () => {
  console.log('Hi From myData._proto_.sayHello!');
}

myData.sayHello();

Result:

But let suppose that we don’t have the method sayHello inside myData object, the first thing that JS will be do is search for the sayHello method inside myData object and because sayHello do not exist inside then JS will search into the Prototype of that object

And because we declared a sayHello function in the prototype of myData object then this function will be executed:

let myData = {
  name: 'Cristina',
  age: 31
}

myData.__proto__.sayHello = () => {
  console.log('Hi From myData._proto_.sayHello!');
}

myData.sayHello();

Result:

By Cristina Rojas.