ts怎样实现,防止类中的属性被直接赋值修改?

`export class Animal {

 privateAttribute
 
 setPrivateAttribute(value) {
        this.privateAttribute = value
    }

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

我想避免在外部直接赋值,就能修改对象内的数据,请问有啥好的想法吗?

阅读 3k
3 个回答
export class Animal {
+ protected privateAttribute
 
 setPrivateAttribute(value) {
   this.privateAttribute = value
 }
}

typescript access modifier

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')
推荐问题