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

177
Vistas
How to simulate protected variables in javascript classes?

What is the best way to simulate protected variables in javascript?

class Parent{

    #variable; // Private variable. This is not to be public.

    constructor(value)
    {
        this.#variable = value;
    }
}

class Child extends Parent{

    getNewVariable()
    {
        return (1 + this.#variable); // Uncaught SyntaxError: Private field '#variable' must be declared in an enclosing class
                                     // We want #variable to be accessible without making it public.
    }
}

Since javascript doesn't support protected variables yet,

What is the best option for accessing private variables from superclasses in extended classes?

I haven't been able to find much documentation on this, so any suggestions would be very helpful.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

What about using TypeScript? TypeScript classes support the protected keyword (see docs), and has alot of extra benefits over vanilla JavaScript.

about 4 years ago · Juan Pablo Isaza Denunciar

0

+++ late answer, but here we go ... +++

A WeakMap based approach most probably covers what the OP is looking for ...

const protectedStatesMap = new WeakMap;

class Parent{
  constructor(foo) {
    protectedStatesMap.set(this, { foo });
  }
  getFoo() {
    return protectedStatesMap.get(this).foo;
  }
}
class Child extends Parent{
  constructor(foo, bar) {
    super(foo);

    Object.assign(protectedStatesMap.get(this), { bar })
  }
  getBar() {
    return protectedStatesMap.get(this).bar;
  }
}
const childA = new Child('foo', 'bar');
const childB = new Child('baz', 'biz');

console.log('childA.getFoo() ...', childA.getFoo());
console.log('childA.getBar() ...', childA.getBar());

console.log('childB.getFoo() ...', childB.getFoo());
console.log('childB.getBar() ...', childB.getBar());
.as-console-wrapper { min-height: 100%!important; top: 0; }

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