What is the difference between prototypes and classes in JavaScript?

Question:

I am doing the "refactoring" of my code and I decided to create a class to have a certain order. To do this I decided to use the prototypes objeto.prototype .

To which I wonder, what difference does it make to create a prototipada class and a common class? that is, between:

class persona {        
    constructor(nombre){
       this.nombre = nombre;
    }

    function saludar(){
        return `hola ${this.nombre}!`;
    }
}

Y

function persona(nombre){
    this.nombre = nombre;
}

persona.prototype.saludar = function (){
    return `hola ${this.nombre}!`;
}

I would like to know if there is any difference and which one would be better to use.

Answer:

Both forms are practically equivalent, the class syntax is syntactic sugar with a slight nuance:

 function persona(nombre){ if (!(this instanceof persona)) { console.log('No actúo como constructor'); } this.nombre = nombre; } persona.prototype.saludar = function (){ return `hola ${this.nombre}!`; } persona('Juan'); p = new persona('yo'); console.log(p); class Persona { constructor(nombre){ this.nombre = nombre; } saludar(){ return `hola ${this.nombre}!`; } } let p2 = new Persona('otro'); console.log(p2); console.log(p2.saludar()); Persona('fallo');

As you can see, a function can be a constructor or a normal function at the same time, but a constructor defined with class syntax cannot be called as if it were a function.

It might sound silly, but native Javascript classes often use constructor functions for other functionality, depending on whether you use new front or not:

let p = Number('5'); //parsea un String, como parseFloat
console.log(p.__proto__.constructor.name,typeof p);

let d = new Number('5'); //crea un objeto Number
console.log(d.__proto__.constructor.name,typeof d);
Scroll to Top