简体   繁体   English

JavaScript:覆盖Date.prototype.constructor

[英]JavaScript: override Date.prototype.constructor

I'd like to change the behaviour of the standard Date object. 我想改变标准Date对象的行为。 Years between 0..99 passed to the constructor should be interpreted as fullYear (no add of 1900 ). 传递给构造函数的0..99之间的年份应解释为fullYear (不添加1900 )。 But my following function doesn't work 但我的以下功能不起作用

var oDateConst = Date.prototype.constructor; // save old contructor

Date.prototype.constructor = function () {
    var d = oDateConst.apply(oDateConst, arguments); // create object with it
    if ( ((arguments.length == 3) || (arguments.length == 6))
        && ((arguments[0] < 100) && (arguments[0] >= 0))) {
        d.setFullYear(arguments[0]);
    }
    return d;
}

Why does it never get called? 它为什么永远不会被召唤? How would you solve this problem? 你会如何解决这个问题?

The reason it never gets called is because you're changing the constructor property on Date.prototype . 永远不会被调用的原因是因为您正在更改Date.prototype上的constructor属性。 However you're probably still creating a date using the code new Date() . 但是,您可能仍在使用代码new Date()创建日期。 So it never uses your constructor. 所以它永远不会使用你的构造函数。 What you really want to do is create your own Date constructor: 你真正想做的是创建自己的Date构造函数:

function MyDate() {
    var d = Date.apply(Date, arguments);
    if ((arguments.length == 3 || arguments.length == 6)
        && (arguments[0] < 100 && arguments[0] >= 0)) {
        d.setFullYear(arguments[0]);
    return d;
}

Then you can create your new date like this: 然后你可以这样创建你的新日期:

var d = MyDate();

Edit: Instead of using Date.apply I would rather use the following instantiate function which allows you to apply arguments to a constructor function : 编辑:而不是使用Date.apply我宁愿使用以下instantiate函数,它允许您将参数应用于构造函数

var bind = Function.bind;
var unbind = bind.bind(bind);

function instantiate(constructor, args) {
    return new (unbind(constructor, null).apply(null, args));
}

This is how I would implement the new date constructor: 这是我实现新日期构造函数的方法:

function myDate() {
    var date = instantiate(Date, arguments);
    var args = arguments.length;
    var arg = arguments[0];

    if ((args === 3 || args == 6) && arg < 100 && arg >= 0)
        date.setFullYear(arg);
    return date;
}

Edit: If you want to override the native Date constructor then you must do something like this: 编辑:如果要覆盖本机Date构造函数,则必须执行以下操作:

Date = function (Date) {
    MyDate.prototype = Date.prototype;

    return MyDate;

    function MyDate() {
        var date = instantiate(Date, arguments);
        var args = arguments.length;
        var arg = arguments[0];

        if ((args === 3 || args == 6) && arg < 100 && arg >= 0)
            date.setFullYear(arg);
        return date;
    }
}(Date);

Piggybacking on Aadit M Shah's native date constructor override - this should be a reply but I don't have enough SO rep for that - as @sakthi mentioned, you'd lose your native Date methods by doing it that way. 捎带Aadit M Shah的原生日期构造函数覆盖 - 这应该是一个回复,但我没有足够的SO代表 - 正如@sakthi提到的那样,你会以这种方式失去你的原生Date方法。 This sucks a bit because Date methods are non-enumerable, so you have to implement a bit of a hack to clone them. 这有点糟糕,因为Date方法是不可枚举的,所以你必须实现一些黑客来克隆它们。

First off, I'd recommend not doing it this way unless you have to. 首先,我建议要这样做,除非你必须这样做。 In my case, I was working in an application with a bunch of legacy code that was constructing dates using the format "md-yyyy", which works in chrome but not safari. 就我而言,我正在使用一堆遗留代码处理一个应用程序,该代码使用格式“md-yyyy”构建日期,该格式适用于chrome但不适用于safari。 I couldn't just do a find/replace in the app, because there were lots of instances where the date strings were being pulled from the service layer or the database. 我不能在应用程序中进行查找/替换,因为有很多实例从服务层或数据库中提取日期字符串。 So, I decided to override the Date constructor in the case where there's a datestring argument in "md-yyyy" format. 所以,我决定在“md-yyyy”格式中有一个datestring参数的情况下覆盖Date构造函数。 I wanted it to be as minimally-invasive as possible, so that it functions as a normal Date otherwise. 我希望它尽可能具有微创性,因此它可以作为正常的日期使用。

Here are my changes - it should allow you to override date with some changes to the constructor, but everything else the same. 以下是我的更改 - 它应该允许您通过对构造函数的一些更改来覆盖日期,但其他所有内容都相同。 You're going to want to change the MyDate constructor before instantiate is called to do whatever you want the constructor to handle. 在调用instantiate之前,您将要更改MyDate构造函数,以执行您希望构造函数处理的任何内容。 This will happen BEFORE the system Date constructor gets applied. 这将在应用系统Date构造函数之前发生。

var bind = Function.bind;
var unbind = bind.bind(bind);

function instantiate(constructor, args) {
    return new (unbind(constructor, null).apply(null, args));
}

Date = function (Date) {

    // copy date methods - this is a pain in the butt because they're mostly nonenumerable
    // Get all own props, even nonenumerable ones
    var names = Object.getOwnPropertyNames(Date);
    // Loop through them
    for (var i = 0; i < names.length; i++) {
        // Skip props already in the MyDate object
        if (names[i] in MyDate) continue;
        // Get property description from o
        var desc = Object.getOwnPropertyDescriptor(Date, names[i]);
        // Use it to create property on MyDate
        Object.defineProperty(MyDate, names[i], desc);
    }

    return MyDate;

    function MyDate() {
        // we only care about modifying the constructor if a datestring is passed in
        if (arguments.length === 1 && typeof (arguments[0]) === 'string') {
            // if you're adding other date transformations, add them here

            // match dates of format m-d-yyyy and convert them to cross-browser-friendly m/d/yyyy
            var mdyyyyDashRegex = /(\d{1,2})-(\d{1,2})-(\d{4})/g;
            arguments[0] = arguments[0].replace(mdyyyyDashRegex, function (match, p1, p2, p3) {
                return p1 + "/" + p2 + "/" + p3;
            });
        }

        // call the original Date constructor with whatever arguments are passed in here
        var date = instantiate(Date, arguments);

        return date;
    }
}(Date);

references: 引用:

With reference to the technique mentioned in Matthew Albert's post, apart from the point which Dan Hlavenka posted, there is one more test scenario which fails. 参考Matthew Albert的帖子中提到的技术,除了Dan Hlavenka发布的那个,还有一个测试场景失败了。 See the following code: 请参阅以下代码:

typeof Date() == typeof new Date()     //Should be false, but it returns true

In a legacy project, there is a chance the above scenario could break few scenarios. 在遗留项目中,上述情况有可能会破坏一些情景。 Apart from the above and what Dan Hlavenka pointed, I agree that this is the most complete solution so far. 除了以上以及Dan Hlavenka所指出的,我同意这是目前为止最完整的解决方案。

Here is a solutions that is very flexible. 这是一个非常灵活的解决方案。 It handles (I believe), all the different cases. 它处理(我相信)所有不同的情况。

DateStub - Allows for stubbing out the Date function. DateStub - 允许删除Date函数。
If you have 'new Date(...). 如果你有'新日期(...)。 ...' sprinkled throughout your code, and you want to test it, this is for you. ......'洒在整个代码中,你想测试它,这是给你的。 It also works with 'moments'. 它也适用于'时刻'。

/**
 * DateStub - Allows for stubbing out the Date function.  If you have
 *      'new Date(...)....' sprinkled throughout your code,
 *      and you want to test it, this is for you.
 *
 * @param {string} arguments Provide 0 to any number of dates in string format.
 *
 * @return a date object corresponding to the arguments passed in.
 *      If you pass only one date in, this will be used by all 'new Date()' calls.
 *      This also provides support for 'Date.UTC()', 'Date.now()', 'Date.parse()'.
 *      Also, this works with the moments library.
 *
 * Examples:
    {   // Test with 1 argument
        Date = DateStub('1/2/2033');        // Override 'Date'

        expect(new Date().toString())
            .toEqual('Sun Jan 02 2033 00:00:00 GMT-0500 (EST)');
        expect(new Date().toString())
            .toEqual('Sun Jan 02 2033 00:00:00 GMT-0500 (EST)');

        Date = DateStub.JavaScriptDate;     // Reset 'Date'
    }
    {   // Call subsequent arguments, each time 'new Date()' is called
        Date = DateStub('1/2/1111', '1/2/1222'
                        , '1/2/3333', '1/2/4444');  // Override 'Date'

        expect(new Date().toString())
            .toEqual('Mon Jan 02 1111 00:00:00 GMT-0500 (EST)');
        expect(new Date().toString())
            .toEqual('Sun Jan 02 1222 00:00:00 GMT-0500 (EST)');
        expect(new Date().toString())
            .toEqual('Fri Jan 02 3333 00:00:00 GMT-0500 (EST)');
        expect(new Date().toString())
            .toEqual('Sat Jan 02 4444 00:00:00 GMT-0500 (EST)');

        Date = DateStub.JavaScriptDate;     // Reset 'Date'
    }
    {   // Test 'Date.now()'.  You can also use: 'Date.UTC()', 'Date.parse()'
        Date = DateStub('1/2/2033');

        expect(new Date(Date.now()).toString())
                .toEqual('Sun Jan 02 2033 00:00:00 GMT-0500 (EST)');

        Date = DateStub.JavaScriptDate;     // Reset 'Date'
    }
 *
 * For more info:  AAkcasu@gmail.com
 */

const DateStub =
    function () {
        function CustomDate(date) {
            if (!!date) { return new DateStub.JavaScriptDate(date); }
            return getNextDate();
        };
        function getNextDate() {
            return dates[index >= length ? index - 1 : index++];
        };

        if (Date.name === 'Date') {
            DateStub.prototype = Date.prototype;
            DateStub.JavaScriptDate = Date;

            // Add Date.* methods.
            CustomDate.UTC = Date.UTC;
            CustomDate.parse = Date.parse;
            CustomDate.now = getNextDate;
        }

        var dateArguments = (arguments.length === 0)
            ? [(new DateStub.JavaScriptDate()).toString()] : arguments
            , length = dateArguments.length
            , index = 0
            , dates = [];
        for (var i = 0; i < length; i++) {
            dates.push(new DateStub.JavaScriptDate(dateArguments[i]));
        }

        return CustomDate;
    };

module.exports = DateStub;

// If you have a test file, and are using node:
// Add this to the top:  const DateStub = require('./DateStub');


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM