How to extend js moment?
I would like to expand moment.js
to override it toJSON
.
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, in this case, I cannot call m2()
without new
:
const json3 = {
date: m2(), // TypeError: Class constructor m2 cannot be invoked without 'new'
};
How can I expand moment
while still being able to call it without a keyword new
?
Override is moment.prototype.toJSON
not a parameter because I would like to use the moment
default object elsewhere in the code.
source to share
Do you need to extend the class moment
at all? You can set a function toJSON
from a factory function.
function m2(data) {
const original = moment(data);
original.toJSON = function() {
return 'STR';
}
return original;
}
Then use it as usual using moment
const json2 = {
date: m2(),
};
source to share