I wanted to know what are the differences between prototype
and __proto__
, in which cases each one is used, how inheritance works and what good practices would be by creating and using objects in javascript.
I wanted to know what are the differences between prototype
and __proto__
, in which cases each one is used, how inheritance works and what good practices would be by creating and using objects in javascript.
First of all we must understand the difference between one and another thing. The prototype
is only present in functions, while the __proto__
is present in all the objects including the functions. Additionally, it must be understood that the __proto__
works as a reference and not as an instance, that is to say that for purposes of working in some object orientation all the objects that you add the object __proto__
will be linked to it. To show a button:
// Implementacion con __proto__
let Humano = {
edad: 0,
tipo_cabello: 'rizado'
};
let persona1 = {
nombre: 'Juan'
};
// Delegando objeto, esto no es una instanciacion
Object.setPrototypeOf(persona1, Humano);
// Ahora puedes hacer
console.log(persona1.edad);
-> 0
// Pero lo que obtienes es esto a cambio
Humano.edad = 1;
console.log(persona1.edad);
-> 1
// Porque persona1 solo tiene como __proto__ (objeto base) a Humano
persona1.__proto__
-> Object {edad: 0, tipo_cabello: "rizado"}
Different to how the prototype works:
// Crea una clase por medio de una funcion
function Perro() {}
Dog.prototype.ladrido = 'ruff';
Dog.prototype.ladrar = function() { console.log(this.ladrido) };
// Instancia esta clase
let doggie = new Perro();
let duke = new Perro();
// Ahora puedes hacer uso de la clase
doggie.ladrar();
-> 'ruff'
// Y si obtienes una instancia
doggie.ladrido = 'atchu';
doggie.ladrar();
-> 'atchu'
duke.ladrar();
-> 'ruff'
The correct implementation of classes and instances would be through functions and the use of new
to create the new instances. I recommend you see the following:
__proto__
is the reference to the prototype of the object.
prototype
is the reference to the prototype that any object created with that function will have.
var Animal = function () {};
var perro = new Animal();
// Modifica el prototipo de perro.
perro.__proto__.sonido = 'guau';
// Modifica el prototipo de los objetos creados con Animal.
Animal.prototype.hablar = function () { console.log(this.sonido); };
perro.hablar(); // Muestra 'guau' en la consola.