Javascript getter:从另一个getter中调用getter

Javascript getter:从另一个getter中调用getter,javascript,reactjs,Javascript,Reactjs,我试图构建一个dateData对象,它看起来像这样: const [dateData] = React.useState({ dateObject: new Date(), get currentYear() { return this.dateObject.getFullYear(); }, get currentMonth() { return this.dateObject.getMonth(); }, get f

我试图构建一个dateData对象,它看起来像这样:

  const [dateData] = React.useState({
    dateObject: new Date(),
    get currentYear() {
      return this.dateObject.getFullYear();
    },
    get currentMonth() {
      return this.dateObject.getMonth();
    },
    get firstDayOfMonth() {
      return this.dateObject(this.currentYear, this.currentMonth).getDay();
    }
  });
代码在
get firstDayOfMonth()
崩溃,表示
this.currentYear不是一个函数
,但getter
get currentYear()
get currentMonth()
正确返回了预期的数据,因此我知道他们正在正确访问
dateObject

我试图实现的目标在Javascript中不可行吗


您的代码有错误。 请更新如下

const [dateData] = React.useState({
    dateObject: new Date(),
    get currentYear() {
      return this.dateObject.getFullYear();
    },
    get currentMonth() {
      return this.dateObject.getMonth();
    },
    get firstDayOfMonth() {
      return new Date(this.currentYear, this.currentMonth, 1);
    }
  });

首先,让我告诉你为什么你的代码会崩溃。 您已经在此处调用/调用了构造函数日期对象:new Date(),。 同样,您试图在下面的方法中调用它,这是错误的,这就是代码崩溃的原因

get firstDayOfMonth() {
      return new Date(this.currentYear, this.currentMonth, 1);
    }
那么解决办法是什么呢?, 您可以通过使用新日期来使用用户>>在上述答案中提供的解决方案

如果您想坚持使用dateObject
dateObject:new date()
中提供的相同日期,则可以尝试以下代码:

get firstDayOfMonth() {
  let bindedDate= Date.bind(this.dateObject)
  return new bindedDate(this.currentYear, this.currentMonth).getDay();
}

返回新日期(this.currentYear,this.currentMonth).getDay();您是从哪里想到使用
React.useState
hook的?在这种情况下,
returnnewbindedate..
您仍然在创建日期对象的新实例,不是吗?那么,这和返回新日期有什么区别?@Mike,是的,我也在创建新的日期实例。您必须创建一个新实例,这是毫无疑问的。我发布的答案是针对一个场景,其中dataObject是在不久前创建的,或者dataObject是像newdate(1995,11,24,10)一样创建的。在这些情况下,用户需要特定日期而不是新日期
返回新日期(this.currentYear…
在此处创建
日期的新实例,对吗?是否有方法使用
日期对象中已存在的相同引用?