Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does moment.js know when it's object is being serialised?

From the moment.js docs

moment().toJSON(); When serializing an object to JSON, if there is a Moment object, it will be represented as an ISO8601 string.

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

I don't understand how the moment object can detect the function operating on it. How is it able to return a different value when serialised, and when simply stored in an object, or returned as a string?

like image 717
Billy Moon Avatar asked Feb 20 '13 22:02

Billy Moon


People also ask

How do you know if an object is a moment object?

isMoment(obj); To check if a variable is a moment object, use moment. isMoment() .

How does moment object get date and time?

With the diff function, we can calculate the difference between two datetime objects. const moment = require('moment'); let d1 = moment('2018-06-12'); let d2 = moment('2018-06-28'); let days = d2. diff(d1, 'days'); console. log(`Difference in days: ${days}`); let hours = d2.

What is a serialized object JavaScript?

The process whereby an object or data structure is translated into a format suitable for transfer over a network, or storage (e.g. in an array buffer or file format). In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.


1 Answers

When using stringify, an object may define how it gets represented, as shown in this documentation:

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

toJSON behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.

For example:

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

moment.js's documentation (seen here: https://raw.github.com/timrwood/moment/2.0.0/moment.js ) shows that this is indeed supported, here is the exact code

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

So, that is how it is aware of how to represent itself when being stringified.

like image 166
Travis J Avatar answered Sep 20 '22 21:09

Travis J