扩展 MomentJS 以覆盖 toString() 函数
Extending MomentJS to override toString() function
我正在尝试将 moment 的 toString 函数扩展为 return 不同格式的日期。
即我想创建如下的 momentDate:
// Will return "Sat Dec 12 2015 00:00:00 GMT+1100"
moment('2015-12-12').toString();
// Will return a custom format, e.g. "2015-12-12"
momentDate('2015-12-12').toString();
我一直在尝试,但没有成功。我不确定它是否可能,因为 moment 是如何写的,所以我想我会在这里问。
我的问题在这里得到了回答:
注意:解决方案适用于 v2.11.0。
function extendedMoment() {
var self = moment();
self.__proto__ = extendedMoment.prototype;
return self;
}
extendedMoment.prototype.__proto__ = moment.prototype;
extendedMoment.prototype.toString = function(){
return this.format('YYYY-MM-DD')
}
document.write("Original: " + moment().toString());
document.write("<br/>");
document.write("Extended: " + extendedMoment().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.js"></script>
我正在尝试将 moment 的 toString 函数扩展为 return 不同格式的日期。
即我想创建如下的 momentDate:
// Will return "Sat Dec 12 2015 00:00:00 GMT+1100"
moment('2015-12-12').toString();
// Will return a custom format, e.g. "2015-12-12"
momentDate('2015-12-12').toString();
我一直在尝试,但没有成功。我不确定它是否可能,因为 moment 是如何写的,所以我想我会在这里问。
我的问题在这里得到了回答:
注意:解决方案适用于 v2.11.0。
function extendedMoment() {
var self = moment();
self.__proto__ = extendedMoment.prototype;
return self;
}
extendedMoment.prototype.__proto__ = moment.prototype;
extendedMoment.prototype.toString = function(){
return this.format('YYYY-MM-DD')
}
document.write("Original: " + moment().toString());
document.write("<br/>");
document.write("Extended: " + extendedMoment().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.js"></script>