【问题标题】:Private properties are behaving like public properties in typescript私有属性的行为类似于打字稿中的公共属性
【发布时间】:2020-06-07 21:28:18
【问题描述】:

我在下面的代码中复制了我在 typescript 中使用私有属性时遇到的问题。

预期行为:只有公共属性应该在我的对象输出中可见,就像在正常封装中一样。

我的目标是使带有 setter 和 getter 的属性成为我的类的公开 api 的一部分,而不是私有属性(如在 C# 中)

 class MyClass {
      public otherProp: boolean;

      constructor() {
          this.otherProp = false;
          this._privateProp = false;
      }

      private _privateProp: boolean;

      get publicProp() : boolean {
        return this._privateProp;
      }

      set publicProp(values : boolean) {
          this._privateProp = values;
      }

    }

    let x: MyClass = new MyClass();

    console.log(x); // MyClass {otherProp: false, _privateProp: false}
                   // Expected output: MyClass {otherProp: false, publicProp: false}

【问题讨论】:

    标签: javascript typescript oop properties


    【解决方案1】:

    您使用# 将属性标记为私有:

    class MyClass {
          public otherProp: boolean;
    
          constructor() {
              this.otherProp = false;
              this.#_privateProp = false;
          }
    
          #_privateProp: boolean;
    
          get publicProp() : boolean {
            return this.#_privateProp;
          }
    
          set publicProp(values : boolean) {
              this.#_privateProp = values;
          }
    
        }
    
        let x: MyClass = new MyClass();
    
        console.log(x); // MyClass {otherProp: false}
    

    【讨论】:

    • 感谢您的回复,我不知道私有财产标记。但我正在寻找一种方法让公共 getter setter 也可见(就像在我的示例中一样),不幸的是在 js 中我不能为 getter/setter 和属性使用相同的名称
    猜你喜欢
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 2014-02-16
    • 1970-01-01
    • 2017-12-09
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多