Adam Adam - 3 years ago 103
Javascript Question

How to extend moment js?

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.

Answer Source

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(),
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download