javascript:将参数传递给对象构造函数 [英] javascript: pass arguments to object constructor

查看:35
本文介绍了javascript:将参数传递给对象构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am writing a jquery lib and i need to implement Datetime functions. i need to create a .Date() function which return a new Date object.

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

How to pass arguments of my .Date(args) function to Date object constructor so to create a new date object?

我试过这样的东西,我是插件命名空间,me=$.jqGUI.

i tried something like this, me is the plugin namespace, 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 但无论如何我都会得到当前日期.如果参数是日期字符串,则将其忽略.为什么?

here i pass to Date.prototype.constructor the arguments but i get in any case the current date. if arguments is a date string it is ignored. why?

推荐答案

对我来说,以下是可行的

ok for me the following was worked

var args = [];
for(var i = 0; i < arguments.length; i++)
   args.push("arguments[" + i + "]");

var d = eval("new Date(" + args.join(",") + ")");   

这篇关于javascript:将参数传递给对象构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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