Classes vs Constructor Functions / Factory Functions

Asked

Viewed 316 times

-1

I’m learning js and I don’t know what the difference is between creating a construction function and creating a class, can anyone explain to me?

1 answer

0


In Javascript everything is done from objects. The most common method of creating and instantiating objects is using a function. For example:

function Carro (marca, cor) {
    this.marca = marca;
    this.cor = cor;
    this.imprimir = function() {
        return this.marca + ' ' + this.cor;
    };
}

The class method was introduced in version ES2015. It includes the word "class" and allows defining the method "constructor".

class Carro {
    constructor(marca, cor) {
        this.marca = marca;
        this.cor = cor;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.