From the MDN documentation:
reviver
(Optional)If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Its name strikes me as odd. Maybe I’m missing a metaphor here — why would this be called “reviving” an object? Is there any history to such a transformer function being called a “reviver”? Googling reviver +javascript
shows that JSON.parse
is basically the only place where this term is used.
The idea is that native Javascript objects, like a Number(42)
, are your "live" objects. When you serialise those into a JSON representation, they're "dried up", or "dumbed down", or whatever you want to call it. To get your fresh live Javascript objects back, you need to "revive" them from their simple text representation.
This becomes more apparent if you use more complex objects:
function Foo(bar) {
this.bar = bar;
}
Foo.prototype.baz = function () {
alert(this.bar);
};
var f = Foo(42);
f.baz();
f = JSON.parse(JSON.stringify(f));
f.baz(); // Nope
To get the original object back which has a baz
method, you need to do a little more than just parse
it. That's the "reviving" part.
The parse
function is used to create an object from data that has been serialized into a string. By default, all it can do is reconstitute the data into plain objects with a bunch of properties.
Sometimes, you may want to "bring these values back to life" (i.e. revive them) into full-fledged objects with methods, behaviors, etc., or even objects that have a particular type, instead of just the lifeless containers of values that JSON.parse()
produces by default.
I would say that's why it's called a reviver
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With