【问题标题】:How to prevent updating attribute directly in js/ts class? [duplicate]如何防止直接在 js/ts 类中更新属性? [复制]
【发布时间】:2021-03-15 03:32:27
【问题描述】:
class Animal {
privateAttribute
setPrivateAttribute(value) {
this.privateAttribute = value
}
}
new Animal().setPrivateAttribute('good way') //ok
new Animal().privateAttribute = 'not allowed' // no
我想直接阻止更新privateAttribute,设置privateAttribute的唯一方法是调用setPrivateAttribute函数。我该怎么办?
【问题讨论】:
标签:
javascript
typescript
【解决方案1】:
请将所有私有变量放入构造函数中。
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')