Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 419
Adam Avatar asked Jul 25 '17 13:07

Adam


People also ask

Can I still use MomentJS?

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.

Is MomentJS being deprecated?

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.

How do you add one day in a moment?

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');


1 Answers

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(),
};
like image 120
Steve Greatrex Avatar answered Sep 25 '22 18:09

Steve Greatrex