【问题标题】:How to extend moment js?如何延长时刻js?
【发布时间】:2017-07-25 13:43:24
【问题描述】:

我想扩展 moment.js,以覆盖它的 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"}

我的问题是,在这种情况下,如果没有new,我就无法调用m2()

const json3 = {
    date: m2(), // TypeError: Class constructor m2 cannot be invoked without 'new'
};

如何扩展moment,同时保留在没有new 关键字的情况下调用它的能力?

重写moment.prototype.toJSON 不是一个选项,因为我想在代码的其他地方使用默认的moment 对象。

【问题讨论】:

  • 为什么不使用辅助函数来实现呢?

标签: javascript ecmascript-6 momentjs


【解决方案1】:

您是否需要扩展 moment 类?您可以设置替换工厂函数中的toJSON 函数。

function m2(data) {
    const original = moment(data);
    original.toJSON = function() {
        return 'STR';
    }
    return original;
}

然后像平常使用moment一样使用它

const json2 = {
    date: m2(),
};

【讨论】:

  • 你没有错过你的 m2 函数的return 语句吗?
  • 我确实做到了 - 现在修复了!
猜你喜欢
  • 2021-08-22
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
  • 2014-11-20
  • 1970-01-01
  • 2021-02-10
  • 2022-01-01
相关资源
最近更新 更多