Search code examples
javascriptjavascript-objects

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


Solution

  • 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)