I'm trying to protect a property of an object from being overwritten by the console. e.g. I have a person object, with a list of allergies as a property. The list of allergies should be able to be modified, however it should always be a list and an error should be thrown if a user tries writing 'person.allergies = "nonsense" '
I've tried looking into Object.freeze() and Object.seal() but cannot get these to work for this purpose, as I don't believe there is a way to unfreeze an object.
class Person {
constructor(name){
this.name = name
this.allergies = []
}
addAllergy(allergy){
this.allergies.push(allergy)
return allergy
}
}
ben = new Person('Ben') // Creating a new Object
ben.addAllergy('Dairy') // Giving the object a new allergy
ben.allergies // Should output ['Dairy']
ben.allergies = 'Soy' // Should make no changes to ben object.