无法覆盖 node.js 中的 Date toString
Can't override Date toString in node.js
在node.js中:
Date.prototype.toString = function dateToString() {
return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
};
console.log("====>", new Date(2019, 0, 1))
我预计是“2019 年 2 月 11 日”,但我得到的却是“2019-01-01T02:00:00.000Z”。
node.js坏了吗?
我觉得node.js没坏。但是你需要调用 toString() 来获取 console.log
中的字符串
Date.prototype.toString = function dateToString() {
return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
};
var date = new Date(2019, 0, 1);
console.log("====>", date.toString());
console.log("====>", date.toDateString());
输出:
====> 2019 年 0 月 1 日
====> 2019 年 1 月 1 日星期二
您可能认为记录 Date
会调用 Date
对象的 toString
函数,因此您可以直接覆盖它 - 但事实并非如此。有些实现会给你类似于 toISOString
的输出,而不是 toString
。在 ECMAScript 规范中没有任何地方定义 console.log
应该如何表现。即使在 the WhatWG Console Standard 中,它也没有描述如何记录 Date
对象 - 所以你处于依赖于实现的领域。
因此,不是覆盖 Date
原型上的函数,您必须 override the console.log
function,检查传递给它的参数是否是 Date
,如果是而是将其转换为字符串,然后将其传递给原始 console.log
函数。我会把它留给你(或其他人)来实施。
或者记得打电话给 .toString()
,正如 ChuongTran 在他们的回答中所显示的那样。
在node.js中:
Date.prototype.toString = function dateToString() {
return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
};
console.log("====>", new Date(2019, 0, 1))
我预计是“2019 年 2 月 11 日”,但我得到的却是“2019-01-01T02:00:00.000Z”。
node.js坏了吗?
我觉得node.js没坏。但是你需要调用 toString() 来获取 console.log
中的字符串 Date.prototype.toString = function dateToString() {
return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
};
var date = new Date(2019, 0, 1);
console.log("====>", date.toString());
console.log("====>", date.toDateString());
输出:
====> 2019 年 0 月 1 日
====> 2019 年 1 月 1 日星期二
您可能认为记录 Date
会调用 Date
对象的 toString
函数,因此您可以直接覆盖它 - 但事实并非如此。有些实现会给你类似于 toISOString
的输出,而不是 toString
。在 ECMAScript 规范中没有任何地方定义 console.log
应该如何表现。即使在 the WhatWG Console Standard 中,它也没有描述如何记录 Date
对象 - 所以你处于依赖于实现的领域。
因此,不是覆盖 Date
原型上的函数,您必须 override the console.log
function,检查传递给它的参数是否是 Date
,如果是而是将其转换为字符串,然后将其传递给原始 console.log
函数。我会把它留给你(或其他人)来实施。
或者记得打电话给 .toString()
,正如 ChuongTran 在他们的回答中所显示的那样。