I'd like to extend moment.js, to override it's toJSON function.
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"}
My problem is that, in this case I can not call m2() without new:
const json3 = {
date: m2(), // TypeError: Class constructor m2 cannot be invoked without 'new'
};
How can I extend moment while keeping the ability to call it without the new keyword?
Override moment.prototype.toJSON is not an option, because I'd like to use the default moment object elsewhere in the code.