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

140
Vistas
How would you access or override a private property of a base class inside a derived class declaration?

How would you do this without:

  • exposing the private property of the base class publicly through setters and getters such as in this answer
  • or having to duplicate any relevant methods and properties of the base class into the derived class

The properties should remain truly private except within the derived class declaration, so you can't use the protected variable underscore _ convention.

Suppose I have the following code

class CoffeeMachine {
  #waterLimit = 600;
  #waterAmount = 0;

  constructor() {}

  set waterAmount(amount) {
    if (amount < 0) {
      this.#waterAmount = 0;
    } else if (amount > this.#waterLimit) {
      this.#waterAmount = this.#waterLimit;
    } else {
      this.#waterAmount = amount;
    }
  }

  get waterAmount() {
    return this.#waterAmount;
  }
}

class TeaMachine extends CoffeeMachine {
  constructor() {
    super();
  }
}

I would like the TeaMachine to be smaller, so I want it's #waterLimit equal to 400 instead of 600

Simply doing the following doesn't work

class TeaMachine extends CoffeeMachine {
  #waterLimit = 400;
  constructor() {
    super();
  }
}

const teaBox = new TeaMachine();
teaBox.waterAmount = 1000;
console.log(teaBox.waterAmount); // 600

This is the closest I could get

The water limit is set on initiation, but is no longer accessible afterwards. Though obviously this is not a perfect solution

class CoffeeMachine {
  #waterLimit;
  #waterAmount = 0;

  constructor(limit = 600) {
    this.#waterLimit = limit;
  }
}

class TeaMachine extends CoffeeMachine {
  constructor() {
    super(400);
  }
}

const teaBox = new TeaMachine();
teaBox.waterAmount = 1000;
console.log(teaBox.waterAmount); // 400

I believe this is possible in Java

Is it even possible to do this in JavaScript while meeting the aforementioned conditions? Or will I have to just accept the restrictions of the language / go down the WeakMap route?

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