Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!