从嵌套在object中的函数访问类属性

时间:2018-05-08 19:24:20

标签: javascript class typescript this

编辑:我已经用更接近实际代码的东西替换了我的初始示例,这仍然表明了同样的问题(在JSFiddle和TypeScript&#39;操场上)。 < / p>

假设我有一个下面定义的Typescript类,其中一个属性由嵌套在另一个对象属性中的getter访问。显然,this getter中的weekdays.monday引用了weekdays,而不是actual

class DayOfWeekSelector {
  private actual = {
    monday: false,
    /*tuesday - sunday would go here*/
  }

  public weekdays = {
    get monday() {
      return this.actual.monday;
    },
    set monday(newVal) {
      this.actual.monday = newVal;
    },
    /*tuesday - sunday would go here*/
  }
}

const dow = new DayOfWeekSelector();

//I want this to read the value of the 'monday' property of the private 'actual' object
//but instead, it tries to read 'actual' as a property of 'weekdays', and fails
console.log(dow.weekdays.monday);

JSFiddle链接:https://jsfiddle.net/dimmreaper/4v6k6ssx/

我知道在这个简单的演示中,我可以直接从对象中将getter中的getter提取到属性中,然后this将引用该类。但是有没有另一种方法可以从类中另一个对象中的getter和setter访问DayOfWeekSelector的属性,而不会增加混乱?

1 个答案:

答案 0 :(得分:2)

不要使用类属性语法,但要在构造函数中显式编写它们,您可以在其中使用局部变量:

class DayOfWeekSelector {
  public weekdays;
  constructor() {
    const actual = {
      monday: false,
      /*tuesday - sunday would go here*/
    };
    this.weekdays = {
      get monday() {
        return actual.monday;
      },
      set monday(newVal) {
        actual.monday = newVal;
      },
      /*tuesday - sunday would go here*/
    };
  }
}
const dow = new DayOfWeekSelector();
console.log(dow.weekdays.monday);

当然,如果那些是你真正的吸气者和制定者除了访问&#34;私人&#34;之外什么都不做。对象,使用它们没有任何好处,直接公开actual对象要简单得多。