I was working with dates and such:
window.onload = () => {
setInterval(
() => {
let currentTimeObj = new Date()
let {currentSeconds: getSeconds()} = currentTimeObj ;
currentTime.innerHTML = `${currentSeconds} `;
}
, 1000);
};
Problem is I want to assign the method from the date object called, getSeconds()
to a variable and use it as a template literal. I'm trying to destructure getDay()
, getHours()
, etc. 'cause I want to do it on one line. If that isn't possible, or isn't reccomended, please tell me.
It outputs, Invalid destructuring assignment target
, I've looked that up on google, I didn't get any clue what to do.
Got any tips? If not all I can think of doing is using the ol' fashioned
"..." + variable + "..."
.
Three issues:
You cannot call a function when that function variable needs to be assigned.
The destructuring syntax
{ a: b } =
will create a variableb
, nota
. So your attempt could have looked like{ getSeconds(): currentSeconds } =
. But the first issue still applies.Even if you assigned the function without attempt to call it, it will not work. If you did:
{ getSeconds: currentSeconds } =
, you would assign thegetSeconds
function tocurrentSeconds
. But for this particular function a correctthis
must be set for it to work. So you would then have to call it ascurrentSeconds.call(currentTimeObj)
, which does not give you the code-saving you would have hoped for.So compare some of the working alternatives: