javascript - 日期构造函数猴子补丁

标签 javascript constructor monkeypatching

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

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

据我所知,javascript 构造函数(调用时)会做三件事:

  1. 它会在执行构造函数时创建一个 this 指向的新对象
  2. 它将此对象设置为委托(delegate)给此构造函数的原型(prototype)。
  3. 它在新创建的对象的上下文中执行构造函数。

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运算符。

PS。重点是我想检查传递给 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/

相关文章:

java - 在Java中,构造函数是非静态的吗?

python - Monkey 修补导入此模块的模块

ruby - 在 ruby​​ 中定义自定义运算符

java - 如何对 jar 中的 .class 文件进行 monkeypatch

javascript - 如何仅在 WooCommerce 结帐页面中启用 Bootstrap css

javascript - 如何使用 createElement 函数在 JavaScript 中的页面加载时创建 div 元素?

c++ - 构造函数链接和初始化语法

javascript - 如何使用正则表达式在全文中查找 URL

javascript - 面对动态数据的 ng-init 问题

c++ - 如何为包含另一个类的类编写构造函数?