日期构造函数猴子补丁 [英] Date constructor monkey patch

查看:95
本文介绍了日期构造函数猴子补丁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修补JavaScript Date 构造函数。
我有以下代码:

I'm trying to monkey patch a javascript Date constructor. I have the following code:

var __Date = window.Date;
window.Date = function(){
    __Date.apply(this, Array.prototype.slice.call(arguments));
};
window.Date.prototype = __Date.prototype;

据我所知,javascript构造函数(在调用时)执行三件事:

As far as I know the javascript constructor (when called) does three things:


  1. 它将创建一个新对象,当执行构造函数时,该对象将指向

  2. 设置该对象以委托给此构造函数的原型。

  3. 在此新创建的对象的上下文中执行构造函数。

Ad.1是通过自动调用新 Date 函数的方式自动完成的( new Date()

Ad.1 is accomplished automatically by the way that the new Date function will be called (new Date())

Ad.2(如果通过设置新的 Date.prototype 成为原始的 Date.prototype

Ad.2 if accomplished by setting my new Date.prototype to be the original Date.prototype.

Ad.3通过调用新创建的对象的上下文中原始的 Date 函数具有与传递给 my的 Date 函数相同的参数

Ad.3 is accomplished by calling the original Date function in the context of the newly created object with the same paramters that are passed to "my" Date function.

以某种方式不起作用。当我打电话给 new Date()。getTime()我收到一条错误消息,指出 TypeError:这不是Date对象。

Somehow it does not work. When i call e.g. new Date().getTime() i get an error saying that TypeError: this is not a Date object.

为什么不起作用?甚至这段代码:

Why doesn't it work? Even this code:

new Date() instanceof __Date

返回 true ,因此通过设置相同的原型,我欺骗了 instanceof 运算符。

returns true so by setting the same prototypes i fooled the instanceof operator.

PS。整个要点是,我想检查传递给 Date 构造函数的参数,并在满足特定条件时更改它们。

PS. the whole point of this is that I want to check the arguments passed to the Date constructor and alter them when a certain condition is met.

推荐答案

感谢@elclanrs提供的链接,我想出了一个可行的解决方案:

Thanks to the link provided by @elclanrs I have come up with a working solution:

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;

问题仍然存在:为什么我的第一次尝试失败了?

Question still remains: why my first attempt didn't work?

这篇关于日期构造函数猴子补丁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆