moment.js如何知道它的对象何时被序列化?

Bil*_*oon 15 javascript datetime date momentjs

从moment.js文档

.力矩()的toJSON(); 将对象序列化为JSON时,如果存在Moment对象,则它将表示为ISO8601字符串.

JSON.stringify({
    postDate : moment()
}); // {"postDate":"2013-02-04T22:44:30.652Z"}
Run Code Online (Sandbox Code Playgroud)

我不明白当时对象如何检测操作它的功能.如何在序列化时返回不同的值,并且只是存储在对象中,还是以字符串形式返回?

Tra*_*s J 24

使用stringify时,对象可以定义它的表示方式,如本文档所示:

来自https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

toJSON行为

如果要进行字符串化的对象具有名为toJSON的属性,其值为函数,则toJSON方法会自定义JSON字符串化行为:而不是被序列化的对象,调用时toJSON方法返回的值将被序列化.

例如:

var x = {
  foo: 'foo',
  toJSON: function () {
    return 'bar';
  }
};
var json = JSON.stringify({x: x});
//json will be the string '{"x":"bar"}'.
Run Code Online (Sandbox Code Playgroud)

moment.js的文档(见这里:https://raw.github.com/timrwood/moment/2.0.0/moment.js )表明这确实是支持的,这里是确切的代码

toJSON : function () {
 return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
Run Code Online (Sandbox Code Playgroud)

所以,这就是它如何在字符串化时表示自己如何表示自己.