【问题标题】:Destructuring a method from an object [duplicate]从对象解构方法[重复]
【发布时间】:2021-01-17 03:38:09
【问题描述】:

我正在处理日期等:

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

问题是我想将调用的日期对象getSeconds() 中的方法分配给一个变量并将其用作模板文字。我正在尝试解构getDay()getHours() 等,因为我想在一条线上进行。如果这不可行或不推荐,请告诉我。

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

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

【问题讨论】:

  • 您的代码等同于let getSeconds() = currentTimeObj.currentSeconds,这是无效的。你想做什么? getSeconds 长什么样子?
  • 哦,对不起,我试图在一行上做;解构其他方法等,我编辑了帖子,谢谢你的澄清。
  • 哦,对不起,我试图在一行上做;解构其他方法等,我编辑了帖子,谢谢你的澄清。

标签: javascript html methods destructuring template-literals


【解决方案1】:

三个问题:

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

  • 解构语法{ 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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2020-04-11
    • 1970-01-01
    • 2018-04-12
    • 2018-11-12
    • 2018-09-04
    • 2012-12-05
    相关资源
    最近更新 更多