我正在编写一个 jquery 库,我需要实现 Datetime 函数。 我需要创建一个返回新日期对象的 .Date() 函数。
如何将我的 .Date(args) 函数的参数传递给 Date 对象构造函数以便创建一个新的日期对象?
我试过这样的东西,我是插件命名空间,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 但无论如何我都会得到当前日期。 如果 arguments 是一个日期字符串,它会被忽略。 为什么?
最佳答案
var args = Array.prototype.concat.apply([null], arguments);
return new (Function.prototype.bind.apply(Date, args));
如果您的目标浏览器不支持 ECMAScript 5 Function.prototype.bind,代码将无法运行。虽然不太可能,请参阅 compatibilty table .
关于javascript:将参数传递给对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11408722/