javascript - How to extend moment js? -
i'd extend moment.js
, 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 that, in case can not call m2()
without new
:
const json3 = { date: m2(), // typeerror: class constructor m2 cannot invoked without 'new' };
how can extend moment
while keeping ability call without new
keyword?
override moment.prototype.tojson
not option, because i'd use default moment
object elsewhere in code.
do need extend moment
class @ all? set replace tojson
function factory function.
function m2(data) { const original = moment(data); original.tojson = function() { return 'str'; } return original; }
then use use moment
const json2 = { date: m2(), };
Comments
Post a Comment