JavaScript:override Date.prototype.constructor [英] JavaScript: override Date.prototype.constructor

查看:365
本文介绍了JavaScript:override Date.prototype.constructor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改标准Date对象的行为。传递给构造函数的 0..99 之间的年应解释为 fullYear (不添加 1900 )。但我的以下函数不起作用

I'd like to change the behaviour of the standard Date object. Years between 0..99 passed to the constructor should be interpreted as fullYear (no add of 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?

推荐答案

它从来没有被调用的原因是因为你改变 > > 的构造函数 c>。但是,您可能仍然使用代码 new Date()创建日期。所以它从不使用你的构造函数。你真正想做的是创建你自己的Date构造函数:

The reason it never gets called is because you're changing the constructor property on Date.prototype. However you're probably still creating a date using the code new Date(). So it never uses your constructor. What you really want to do is create your own Date constructor:

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();

编辑:而不是使用 Date.apply 我宁愿使用下面的 instantiate 函数,它允许你将参数应用于构造函数

Instead of using Date.apply I would rather use the following instantiate function which allows you to apply arguments to a constructor function:

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;
}

编辑:如果要覆盖原生Date构造函数,那么你必须这样做:

If you want to override the native Date constructor then you must do something like this:

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);

这篇关于JavaScript:override Date.prototype.constructor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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