我想扩展moment.js
,覆盖它的toJSON
函数。如何延长js时间?
const moment = require('moment');
class m2 extends moment {
constructor(data) {
super(data);
this.toJSON = function() {
return 'STR';
};
}
}
const json = {
date: moment(),
};
const json2 = {
date: new m2(),
};
console.log(JSON.stringify(json)); // {"date":"2017-07-25T13:36:47.023Z"}
console.log(JSON.stringify(json2)); // {"date":"STR"}
我的问题是,在这种情况下,我不能叫m2()
没有new
:
const json3 = {
date: m2(), // TypeError: Class constructor m2 cannot be invoked without 'new'
};
如何延长moment
,同时保持叫它没有new
关键字的能力吗?
覆盖moment.prototype.toJSON
不是一个选项,因为我想在代码的其他地方使用默认的moment
对象。
你为什么不使用辅助函数来实现这一目标? –