Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Static and Instance methods defined in a class vs directly on prototype

Are there any differences between the following two class constructions, other than the first being synactic sugar for the second?

class Number {
    constructor(number) {
        this.number = number;
    }
    toString() {
        return `${this.number}`;
    }
    plus(that) {
        return new Number(this.number + that.number);
    }
    static sum(c, d) {
        return c.plus(d);
    }
}
const c1 = new Number(2);
const c2 = new Number(3);
console.log(c1.plus(c2) + "");
console.log(Number.sum(c1,c2) + "");

class Number {
    constructor(number) {
        this.number = number;
    }
}
// instance methods are on the prototype
Number.prototype.toString = function toString() {
    return `${this.number}+${this.number}i`;
}
Number.prototype.plus = function plus(that) {
    return new Number(this.number * that.number);
}
// static methods are directly on the class
Number.sum = function sum(c, d) {
    return c.plus(d);
}
const c1 = new Number(2);
const c2 = new Number(3);
console.log(c1.plus(c2) + "");
console.log(Number.sum(c1,c2) + "");

Additionally, why can't I define the constructor on the class as follows (doing so just returns undefined for all the variables):

class Number {}
Number.prototype.constructor = function constructor(number) {
    this.number = number;
}
console.log(new Number(2));

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda