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

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -