我需要修改 JavaScript 的日期对象。我唯一需要更改的是 new Date()
,我需要始终返回相同的日期。
有一个关于通过偏移量更改日期的类似问题,但我想知道我是否可以用更少的代码做同样的事情?: Monkeypatch the JavasScript date object
修改上面问题的代码我有一个解决方案可以解决这个问题:
Date = (function(oldDate) {
/**
* @return {string}
*/
function Date(year, month, date, hours, minutes, seconds, ms) {
let res;
const l = arguments.length;
if (l == 0) {
res = new oldDate(Date.now());
} else if (l == 1) {
res = new oldDate(year); // milliseconds since epoch, actually
} else {
res = new oldDate(
year,
month,
l > 2 ? date : 1,
l > 3 ? hours : 0,
l > 4 ? minutes : 0,
l > 5 ? seconds : 0,
l > 6 ? ms : 0,
);
}
if (this instanceof Date) {
return res;
}
return res.toString();
}
Date.prototype = oldDate.prototype; // required for instanceof checks
Date.now = function() {
return 1570705688585; // HERE I REUTRN A FIXED DATE
};
Date.parse = oldDate.parse;
Date.UTC = oldDate.UTC;
return Date;
})(Date, Date.now);
查看这些文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
似乎 Date.now
有一个你可以使用的 pollyfill:
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
我试过了,但没有效果:
Date.now = function now() {
return 1570705688585;
};
最佳答案
您可能无法仅更改 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"))
关于javascript - 猴子补丁 JavaScript new Date(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58321972/