通过调用prototype.constructor.apply实例化一个JavaScript对象

2024-04-24

让我从一个具体的例子开始,说明我正在尝试做的事情。

我有一系列的年、月、日、小时、分钟、秒和毫秒组件,格式为[ 2008, 10, 8, 00, 16, 34, 254 ]。我想使用以下标准构造函数实例化 Date 对象:

new Date(year, month, date [, hour, minute, second, millisecond ])

如何将数组传递给此构造函数以获取新的 Date 实例?[ Update:我的问题实际上超出了这个具体示例。我想要一个针对内置 JavaScript 类(如 Date、Array、RegExp 等)的通用解决方案,这些类的构造函数超出了我的能力范围。 ]

我正在尝试做类似以下的事情:

var comps = [ 2008, 10, 8, 00, 16, 34, 254 ];
var d = Date.prototype.constructor.apply(this, comps);

我可能需要一个“new“在某处。上面的代码只是返回当前时间,就好像我调用了“(new Date()).toString()”。我也承认我的上述观点可能完全错误:)

Note: No eval()请不要一一访问数组项。我很确定我应该能够按原样使用该数组。


我自己做了更多的调查并得出了这样的结论:这是不可能的壮举,由于 Date 类的实现方式。

我已经检查过蜘蛛猴 http://www.mozilla.org/js/spidermonkey/源代码以查看日期是如何实现的。我认为这一切都可以归结为以下几行:

static JSBool
Date(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    jsdouble *date;
    JSString *str;
    jsdouble d;

    /* Date called as function. */
    if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
        int64 us, ms, us2ms;
        jsdouble msec_time;

        /* NSPR 2.0 docs say 'We do not support PRMJ_NowMS and PRMJ_NowS',
         * so compute ms from PRMJ_Now.
         */
        us = PRMJ_Now();
        JSLL_UI2L(us2ms, PRMJ_USEC_PER_MSEC);
        JSLL_DIV(ms, us, us2ms);
        JSLL_L2D(msec_time, ms);

        return date_format(cx, msec_time, FORMATSPEC_FULL, rval);
    }

    /* Date called as constructor. */
    // ... (from here on it checks the arg count to decide how to create the date)

当 Date 用作函数时(或者作为Date() or Date.prototype.constructor(),它们是完全相同的),它默认以区域设置格式的字符串形式返回当前时间。这与传入的任何参数无关:

alert(Date()); // Returns "Thu Oct 09 2008 23:15:54 ..."
alert(typeof Date()); // Returns "string"

alert(Date(42)); // Same thing, "Thu Oct 09 2008 23:15:54 ..."
alert(Date(2008, 10, 10)); // Ditto
alert(Date(null)); // Just doesn't care

我不认为在 JS 级别可以做任何事情来规避这个问题。而这大概就是我对这个话题的追求的结束了。

我还注意到一些有趣的事情:

    /* Set the value of the Date.prototype date to NaN */
    proto_date = date_constructor(cx, proto);
    if (!proto_date)
        return NULL;
    *proto_date = *cx->runtime->jsNaN;

Date.prototype是一个 Date 实例,其内部值为NaN因此,

alert(Date.prototype); // Always returns "Invalid Date"
                       // on Firefox, Opera, Safari, Chrome
                       // but not Internet Explorer

IE没有让我们失望。它的做法有点不同,可能将内部值设置为-1这样 Date.prototype 总是返回一个稍早于纪元的日期。


Update

我终于深入研究了 ECMA-262 本身,事实证明,我想要实现的(使用 Date 对象)——根据定义——是不可能的:

15.9.2 作为函数调用的日期构造函数

当 Date 被称为 函数而不是构造函数, 它返回一个表示 当前时间 (UTC)。

NOTE功能 称呼Date(…)不等于 对象创建表达式new Date(…)具有相同的论点。

15.9.2.1 日期 ([ 年 [ 月 [ 日期 [ 小时 [ 分钟 [ 秒 [ 多发性硬化症 ] ] ] ] ] ] ] )

全部 参数是可选的;任何论据 所提供的已被接受,但 完全被忽略了。一个字符串是 创建并返回,就像由 表达(new Date()).toString().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过调用prototype.constructor.apply实例化一个JavaScript对象 的相关文章