gpt4 book ai didi

javascript - 无法在 Javascript 中延长日期?

转载 作者:行者123 更新时间:2023-11-30 12:23:05 27 4
gpt4 key购买 nike

我写了这个愚蠢的简单日期扩展,但我不确定它为什么不起作用:

function ToShortDateString(){
var cur_date = this;
if(!cur_date instanceof Date){
return 'Not A Date';
}
if(Date.parse('2/6/2009')=== 1233896400000){
return [cur_date.getMonth()+1, cur_date.getDate(), cur_date.getFullYear()].join('/');
}
return [cur_date.getDate(), cur_date.getMonth()+1, cur_date.getFullYear()].join('/');
}
Date.prototype.toShortDateString = ToShortDateString;

当我执行以下操作时,它会爆炸:

var myDate = Date();
var myString = myDate.toShortDateString();

为什么我的原型(prototype)扩展没有被添加到新的 Date 对象中?

最佳答案

问题在于您调用 Date 构造函数的方式。日期需要新的运算符。目前你正在 myDate 中存储一个字符串

var mydate = Date(); // string
var otherDate = new Date(); // Date

更简洁

Date() instanceof Date // false
new Date() instanceof Date // true

关于javascript - 无法在 Javascript 中延长日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com