从对象中解构方法
Destructuring a method from an object
我正在处理日期等:
window.onload = () => {
setInterval(
() => {
let currentTimeObj = new Date()
let {currentSeconds: getSeconds()} = currentTimeObj ;
currentTime.innerHTML = `${currentSeconds} `;
}
, 1000);
};
问题是我想将调用的日期对象 getSeconds()
中的方法分配给一个变量,并将其用作模板文字。我正在尝试解构 getDay()
、getHours()
等,因为我想在一行中完成。如果这不可能,或者不推荐,请告诉我。
它输出 Invalid destructuring assignment target
,我已经在 google 上查过了,我不知道该怎么做。
有什么建议吗?如果不是我能想到的就是使用老式的
"..." + variable + "..."
.
三期:
当函数变量需要赋值时,您不能调用函数。
解构语法 { a: b } =
将创建一个变量 b
,而不是 a
。所以你的尝试可能看起来像 { getSeconds(): currentSeconds } =
。但是第一个问题仍然适用。
即使您在没有尝试调用的情况下分配了函数,它也不会起作用。如果您这样做:{ getSeconds: currentSeconds } =
,您会将 getSeconds
函数分配给 currentSeconds
。但是对于这个特定的功能,必须设置正确的 this
才能工作。因此,您必须将其称为 currentSeconds.call(currentTimeObj)
,这不会给您带来您希望的 code-saving。
所以比较一些可行的替代方案:
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());
我正在处理日期等:
window.onload = () => {
setInterval(
() => {
let currentTimeObj = new Date()
let {currentSeconds: getSeconds()} = currentTimeObj ;
currentTime.innerHTML = `${currentSeconds} `;
}
, 1000);
};
问题是我想将调用的日期对象 getSeconds()
中的方法分配给一个变量,并将其用作模板文字。我正在尝试解构 getDay()
、getHours()
等,因为我想在一行中完成。如果这不可能,或者不推荐,请告诉我。
它输出 Invalid destructuring assignment target
,我已经在 google 上查过了,我不知道该怎么做。
有什么建议吗?如果不是我能想到的就是使用老式的
"..." + variable + "..."
.
三期:
当函数变量需要赋值时,您不能调用函数。
解构语法
{ a: b } =
将创建一个变量b
,而不是a
。所以你的尝试可能看起来像{ getSeconds(): currentSeconds } =
。但是第一个问题仍然适用。即使您在没有尝试调用的情况下分配了函数,它也不会起作用。如果您这样做:
{ getSeconds: currentSeconds } =
,您会将getSeconds
函数分配给currentSeconds
。但是对于这个特定的功能,必须设置正确的this
才能工作。因此,您必须将其称为currentSeconds.call(currentTimeObj)
,这不会给您带来您希望的 code-saving。
所以比较一些可行的替代方案:
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());