我正在尝试修补 javascript Date
构造函数。
我有以下代码:
var __Date = window.Date;
window.Date = function(){
__Date.apply(this, Array.prototype.slice.call(arguments));
};
window.Date.prototype = __Date.prototype;
据我所知,javascript 构造函数(调用时)会做三件事:
- 它会在执行构造函数时创建一个
this
指向的新对象 - 它将此对象设置为委托(delegate)给此构造函数的原型(prototype)。
- 它在新创建的对象的上下文中执行构造函数。
Ad.1 通过调用新的 Date
函数 (new Date()
) 自动完成
Ad.2 如果通过将我的新 Date.prototype
设置为原始 Date.prototype
来完成。
Ad.3 是通过在新创建的对象的上下文中调用原始 Date
函数来完成的,该函数具有传递给“my”Date
函数的相同参数。
不知怎的,它不起作用。当我打电话时new Date().getTime()
我收到一条错误,指出 TypeError: this is not a Date object.
为什么不起作用?甚至这个代码:
new Date() instanceof __Date
返回true
,因此通过设置相同的原型(prototype),我愚弄了instanceof
运算符。
Date
构造函数的参数,并在满足特定条件时更改它们。
最佳答案
感谢@elclanrs 提供的链接,我想出了一个可行的解决方案:
var __Date = window.Date;
window.Date = function f(){
var args = Array.prototype.slice.call(arguments);
// Date constructor monkey-patch to support date parsing from strings like
// yyyy-mm-dd hh:mm:ss.mmm
// yyyy-mm-dd hh:mm:ss
// yyyy-mm-dd
if(typeof args[0] === "string" && /^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2}(\.\d{3})?)?$/.test(args[0])){
args[0] = args[0].replace(/-/g, '/').replace(/\.\d{3}$/, '');
}
args.unshift(window);
if(this instanceof f)
return new (Function.prototype.bind.apply(__Date, args));
else
return __Date.apply(window, args);
};
// define original Date's static properties parse and UTC and the prototype
window.Date.parse = __Date.parse;
window.Date.UTC = __Date.UTC;
window.Date.prototype = __Date.prototype;
问题仍然存在:为什么我的第一次尝试没有成功?
关于javascript - 日期构造函数猴子补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22400161/