0
class Animal {

 privateAttribute
 
 setPrivateAttribute(value) {
        this.privateAttribute = value
    }
}
new Animal().setPrivateAttribute('good way') //ok 
new Animal().privateAttribute = 'not allowed' // no

I want to prevent update privateAttribute directly, the only way to set privateAttribute is call setPrivateAttribute function. What shold I do?

domakun
  • 3
  • 1

1 Answers1

0

Please put all the private variable inside your constructor.

class Animal {
  constructor() {
    let privateAttribute = 'default';

    this.setPrivateAttribute = newValue => {
      privateAttribute = newValue
    }

    this.getPrivateAttribute = () => privateAttribute;
  }
}

let newAnimal = new Animal()
// get variable value
newAnimal.getPrivateAttribute()

// Set new Value
newAnimal.setPrivateAttribute('New Value')