我需要猴子修补JavaScript的date对象。我唯一需要更改的是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
有一个可以使用的填满:
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
我尝试过,但是没有任何影响:
Date.now = function now() {
return 1570705688585;
};
答案 0 :(得分:1)
您可能无法仅更改const data = [
{ id: 1, names: ['A', 'B'] },
{ id: 2, names: ['C'] },
]
const selectedNames = [
{ name: 'A', selected: true },
{ name: 'D', selected: true },
{ name: 'B', selected: true },
]
const result = [];
for (const element of data) {
for (const name of selectedNames) {
if (element.names.includes(name.name) && !result.includes(element)) {
result.push(element);
}
}
}
console.log( result );
,因为构造函数可能不会调用该方法。但是,您可以通过直接复制所有属性并仅覆盖Date.now
和零参数构造函数来使补丁程序更短:
Date.now