Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';不能用Javascript扩展日期?_Javascript - Fatal编程技术网

Can';不能用Javascript扩展日期?

Can';不能用Javascript扩展日期?,javascript,Javascript,我写了这个愚蠢的简单日期扩展,我不知道为什么它不起作用: 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_

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

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();

为什么我的原型扩展没有添加到新的日期对象中?

问题在于调用日期构造函数的方式。日期需要新的操作员。当前,您正在myDate中存储字符串

var mydate = Date(); // string
var otherDate = new Date(); // Date
更简洁

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

@Nathanteregillus这发生在我们中最好的人身上。JS型系统已经被打破了几十年。你回答得很快。还要再等6分钟