Ada*_*dam 3 javascript momentjs ecmascript-6
我想扩展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"}
Run Code Online (Sandbox Code Playgroud)
我的问题是,在这种情况下,我不能叫m2()无new:
const json3 = {
date: m2(), // TypeError: Class constructor m2 cannot be invoked without 'new'
};
Run Code Online (Sandbox Code Playgroud)
如何moment保持在没有new关键字的情况下调用它的能力?
覆盖moment.prototype.toJSON不是一个选项,因为我想moment在代码中的其他地方使用默认对象.
你需要扩展moment课程吗?您可以设置toJSON从工厂功能替换功能.
function m2(data) {
const original = moment(data);
original.toJSON = function() {
return 'STR';
}
return original;
}
Run Code Online (Sandbox Code Playgroud)
然后像平常一样使用它 moment
const json2 = {
date: m2(),
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
758 次 |
| 最近记录: |