从对象破坏方法

问题描述

我正在处理日期,例如:

window.onload = () => {
  setInterval(
    () => {
      
      
      let currentTimeObj = new Date()
      
      let {currentSeconds: getSeconds()} = currentTimeObj ;
      
      currentTime.innerHTML = `${currentSeconds} `;
      
      
    },1000);
};

问题是我想将称为getSeconds()的日期对象中的方法分配给变量,并将其用作模板文字。我试图破坏getDay()getHours() 等,因为我想一行完成。如果这不可能或不建议,请告诉我。

输出Invalid destructuring assignment target,我在Google上查询过,我不知道该怎么做。

有什么建议吗?如果不是所有我能想到的就是使用ol' "..." + variable + "..."

解决方法

三个问题:

  • 当需要分配该函数变量时,您不能调用一个函数。

  • 解构语法{ a: b } = 将创建变量b,而不是a。因此,您的尝试可能看起来像{ getSeconds(): currentSeconds } =。但是第一个问题仍然适用。

  • 即使您在未尝试调用功能的情况下分配了该功能,也无法使用。如果您这样做:{ getSeconds: currentSeconds } =,则需要将getSeconds函数分配给currentSeconds。但是,对于此特定功能,必须设置正确的this才能起作用。因此,您必须将其命名为currentSeconds.call(currentTimeObj),但这并不能为您节省代码。

因此比较一些可行的替代方案:

let currentTimeObj = new Date();
// Longer:
let {getSeconds: currentSeconds} = currentTimeObj;
console.log(currentSeconds.call(currentTimeObj));
// Alternative,still long:
currentSeconds = currentTimeObj.getSeconds.bind(currentTimeObj);
console.log(currentSeconds());
// Shorter:
console.log(currentTimeObj.getSeconds());