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

182
Vistas
How to prevent function contructor arrays from being edited via get methods in JavaScript?

I have this code

function State(){
  const SecretState = {
    name: 'bob'
  }
  this.getState = () => SecretState;
  this.setState = (name) => SecretState.name = name;
}
const m = new State()

m.setState('Smith')

m.getState().name = 'Alice'

console.log(m.getState().name)

At the final console log, I should get "Smith". I want to prevent the ability to set the state within the getState method

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

0

Issue is, in JS objects are copied using reference. So getState is returning a reference instead of object.

Try updating to this instead:

this.getState = () => ({...SecretState});

What this does is it creates a new object and pass its reference. This way your SecretState is accessible only using setter. However, this will not work if you have deep nested objects as Object spread only works for first level

function State(){
  const SecretState = {
    name: 'bob'
  }
  this.getState = () => ({...SecretState});
  this.setState = (name) => SecretState.name = name;
}
const m = new State()

m.setState('Smith')

m.getState().name = 'Alice'

console.log(m.getState().name)

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