Destructuring a method from an object

424 views Asked by At

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 + "..." .

1

There are 1 answers

0
trincot On BEST ANSWER

Three issues:

  • You cannot call a function when that function variable needs to be assigned.

  • The destructuring syntax { a: b } = will create a variable b, not a. 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 the getSeconds function to currentSeconds. But for this particular function a correct this must be set for it to work. So you would then have to call it as currentSeconds.call(currentTimeObj), which does not give you the code-saving you would have hoped for.

So compare some of the working alternatives:

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());