Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda