I\'m trying to subclass/extend the native Date object, without modifying the native object itself.
I\'ve tried this:
var util = require(\'util\')
var SubDate = function() {
var dateInst = new Date(...arguments); // spread arguments object
/* Object.getPrototypeOf(dateInst) === Date.prototype */
Object.setPrototypeOf(dateInst, SubDate.prototype); // redirectionA
return dateInst; // now instanceof SubDate
};
Object.setPrototypeOf(SubDate.prototype, Date.prototype); // redirectionB
// do something useful
Object.defineProperty(SubDate.prototype, 'year', {
get: function() {return this.getFullYear();},
set: function(y) {this.setFullYear(y);}
});
var subDate = new SubDate();
subDate.year; // now
subDate.year = 2050; subDate.getFullYear(); // 2050
The problem with the Date constructor function is already explained in the other answers. You can read about the Date.call(this, ...arguments) problem on Date | MDN (first Note).
This solution is a compact workaround which works as intended in all supporting browsers.