如何解决从对象破坏方法
我正在处理日期,例如:
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());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。