0

Some objects in Javascript, such as Date, have two types of constructors.

Date()

When called as a function, returns a string representation of the current date and time, exactly as new Date().toString() does.

new Date()

When called as a constructor, returns a new Date object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#constructor

For some objects, like Date, that I need to extend I can use class extend to override the constructor to add additional functionality. While that works great when used when the object is initialized with the new keyword, if you use try to use the function type constructor it fails with

TypeError: Class constructor cannot be invoked without 'new'

So how can you extend an existing object so that both types of constructors remain viable?

barneyAgumble
  • 167
  • 1
  • 7
  • 1
    I don't think you can do this using `class` syntax. You need to use the older prototype syntax. The constructor function can check whether `this` is set to an instance of the class. – Barmar Nov 09 '21 at 00:38
  • "*When called as a function, returns a string*" - that is not a constructor. – Bergi Nov 09 '21 at 00:41
  • 1
    "*For some objects, like Date, that I need to extend*" - you really should not extend `Date`. Why do you think you needed to? – Bergi Nov 09 '21 at 00:44

0 Answers0