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

81
Vistas
Overwrite empty string in Javascript object

I need that child class StringBuilder would pass the string to the parent class and call the minus method. The following code does not work unless I won't hardcode the string in the constructor. With numbers this works just fine. Why doesn't it overwrite the string? Or maybe I'm doing everything completely wrong?

class Builder {
    constructor() {
        this.int = 0
        this.str = ''
    }

    minus(...n) {
        this.int = n.reduce((sum, current) => sum - current, this.int)
        this.str = this.str.slice(0, -n)
        return this
    }
}

class IntBuilder extends Builder {
    constructor(int) {
        super(int)
    }
}

class StringBuilder extends Builder {
    constructor(str) {
        super(str)
    }
}

let number = new IntBuilder()
number.minus(100, 99)

console.log(number)

let string = new StringBuilder('Hello')

string.minus(2)

console.log(string)
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your Builder constructor does not take any parameters. Declare a parameter and assign that parameter to this.str. You can use default parameters to ensure it will be initialized to whatever you want even when the constructor is called without parameters.

class Builder {
  constructor(str = "") {
    this.int = 0
    this.str = str
  }

  minus(...n) {
    this.int = n.reduce((sum, current) => sum - current, this.int)
    this.str = this.str.slice(0, -n);
    return this;
  }
}

class IntBuilder extends Builder {
  constructor(int) {
    super(int)
  }
}

class StringBuilder extends Builder {
  constructor(str) {
    super(str)
  }
}

let number = new IntBuilder()
number.minus(100, 99)

console.log(number)

let string = new StringBuilder('Hello')

string.minus(2)

console.log(string)

about 4 years ago · Juan Pablo Isaza Denunciar
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