2017-07-25 103 views
3

我想扩展moment.js,覆盖它的toJSON函数。如何延长js时间?

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"} 

我的问题是,在这种情况下,我不能叫m2()没有new

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

如何延长moment,同时保持叫它没有new关键字的能力吗?

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

+0

你为什么不使用辅助函数来实现这一目标? –

回答

5

您是否需要扩展moment类?您可以使用工厂功能替换toJSON功能。

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

然后使用它,你通常会使用moment

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

难道你不想念m2函数的'return'语句吗? –

+0

我确定 - 现在修好了! –