For context, I am trying to re-create the native Date object to better suit my purposes, for this I am extending it with a class, for a basic example:
class MyDate extends Date {
constructor(...input) {
super(...input);
this.change = 'example change';
return this;
}
}
In most ways I have succeeded at my task, my NewDate class works nicely, and almost fully matching in behavior with the native Date class, however it has one little difference:
console.log(Date()); // this works, printing your current date as a string
console.log(MyDate()); // doesn't work, gives the error below:
// Uncaught TypeError: Class constructor MyDate cannot be invoked without 'new'
So how can I replicate Date's behavior of being both a class constructor and a function at the same time? Obviously it is possible otherwise Date wouldn't be able to do it.
I have already tried:
- Messing with prototypes (
.prototypeand.__proto__) although there's so many ways to tamper with those I wouldn't be surprised I missed some very obscure caveat with them. - Making a function called
MyDatewhich returns the string or my class constructor, which actually does work but breaksnew MyDate instanceof Date(since it becomes an instance of a Function instead) - Every top answer on this question: How to extend Function with ES6 classes? | They all worked in some way but broke in another.