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.
Conclusion. MomentJS isn't completely gone yet. But on their website they suggest you look beyond Moment unless you fall into specific usecases. Luxon seems to be the biggest replacement for Moment that is futureproof for now.
MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week. With that I began a journey during a Hackathon to replace moment in a core library at my company.
This is a pretty robust function for adding time to an existing moment. To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');
Do you need to extend the moment
class at all? You could set replace the toJSON
function from a factory function.
function m2(data) {
const original = moment(data);
original.toJSON = function() {
return 'STR';
}
return original;
}
Then use it as you would normally use moment
const json2 = {
date: m2(),
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With