javascript:将参数传递给对象构造函数

2024-03-10

我正在编写一个jquery lib,我需要实现日期时间函数。 我需要创建一个 .Date() 函数,它返回一个新的 Date 对象。

如何将 .Date(args) 函数的参数传递给 Date 对象构造函数以创建新的日期对象?

我尝试了这样的方法,me是插件命名空间,me=$.jqGUI。

        //.Date(Value)
        /* Return a date object.
         * ReturnValue = Date(Value)
         */
        me.Date = function(Value){
            //pass arguments to Date constructor
            var sDate = Date.prototype.constructor.apply(null, arguments);

            console.log(sDate);

            //create a date object d
            var d = new Date(sDate);

            //validate date object
            if(d.toDateString()=="Invalid Date"){
                throw new Error("$.jqGUI.Date: Invalid Date");
            }
            else{
                return d;                   
            }
        };

在这里我将参数传递给 Date.prototype.constructor 但无论如何我都会得到当前日期。 如果参数是日期字符串,则会被忽略。 为什么?


var args = Array.prototype.concat.apply([null], arguments);
return new (Function.prototype.bind.apply(Date, args));

如果您的目标浏览器不支持 ECMAScript 5 Function.prototype.bind,则代码将无法运行。不过可能性不大,请参阅兼容性表 http://kangax.github.io/compat-table/es5/#Function.prototype.bind.

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

javascript:将参数传递给对象构造函数 的相关文章

随机推荐