【问题标题】: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')
    

    【讨论】:

    • 非常感谢!这正是我想要的哈哈
    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 2023-03-04
    • 2011-09-06
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多