1

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 (.prototype and .__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 MyDate which returns the string or my class constructor, which actually does work but breaks new 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.
jhm2k
  • 53
  • 9
  • 1
    ES6 `class`es are not callable, only constructable. You need to use ES5 `function` syntax in order to define classes that are both callable and constructable. – Patrick Roberts May 12 '21 at 00:47
  • 1
    I'm assuming just using `new MyDate()` wont work for. you? – maxshuty May 12 '21 at 00:49
  • 1
    Closely related [ES6: call class constructor without new keyword](https://stackoverflow.com/q/30689817/364696). I see a hint of an answer in the existence of `call constructor`s in newer versions of the standard mentioned in the comments, but don't know anything about 'em. – ShadowRanger May 12 '21 at 00:52
  • [This](https://stackoverflow.com/a/31789308/1048572) should do. No, you don't want to `extend Function`. – Bergi May 12 '21 at 01:09

0 Answers0