Возможно, вы не сможете просто изменить Date.now
, так как конструктор может не вызывать этот метод. Однако вы можете сделать патч короче, напрямую скопировав все свойства и переписав Date.now
и конструктор с нулевым аргументом:
//keep for testing
const OriginalDateConstructor = Date;
Date = (function(oldDate) {
function Date(...args) {
if (args.length === 0) {
//override the zero argument constructor
return new oldDate(Date.now())
}
//else delegate to the original constructor
return new oldDate(...args);
}
//copy all properties from the original date, this includes the prototype
const propertyDescriptors = Object.getOwnPropertyDescriptors(oldDate);
Object.defineProperties(Date, propertyDescriptors);
//override Date.now
Date.now = function() {
return 1570705688585;
};
return Date;
})(Date);
console.log("same prototype", Object.getPrototypeOf(Date) === Object.getPrototypeOf(OriginalDateConstructor))
console.log("no argument", new Date());
console.log("single argument - zero", new Date(0));
console.log("single argument - non-zero", (new Date(new OriginalDateConstructor("2019-01-01").getTime())));
console.log("passing ISO string", new Date("2019-06-01"));
console.log("passing year, month", new Date(2019, 09));
console.log("passing year, month, day", new Date(2019, 09, 15));
console.log("passing year, month, day, hour", new Date(2019, 09, 15, 10));
console.log("passing year, month, day, hour, minutes", new Date(2019, 07, 15, 10, 30));
console.log("passing year, month, day, hour, minutes, seconds", new Date(2019, 07, 15, 10, 30, 45));
console.log("passing in a date", new Date(new Date("2019-03-01")))
console.log("conversion to number", +new Date("2019-06-01T12:00"))
console.log("implicit conversion to string", "" + new Date("2019-06-01T12:00"))