Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda