为什么JSON.stringify()接受Date对象?

Thi*_*ter 12 javascript json date

至少在Firefox中,您可以对Date对象进行字符串化:

>>> JSON.stringify({'now': new Date()})
'{"now":"2012-04-23T18:44:05.600Z"}'
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为(在Firefox中)Date包含toJSON其JSON序列化程序使用的方法.但是,这不是JSON标准的一部分,所以我想知道为什么这个方法存在,或者为什么内置JSON序列化器检查这样的方法.由于它没有标准化,所以无论如何都不能安全地使用它,如果内置的序列化器理解它并且使用自定义的(例如json2.js)

Cha*_*ion 11

这是有效的,因为它在规范中的不太明确的内容中指定.首先,您需要深入了解抽象操作Str的描述中的第15.12.3节,该操作用于将值转换为字符串表示.基本上,如果输入是一个对象,则规范要求检查是否存在名为的可调用值.可以把它想象成Java或C#中的接口.toJSON

interface IAmJSON 
{
    string toJSON(string key);
}
Run Code Online (Sandbox Code Playgroud)

这是规范中的确切文本.

2.  If Type(value) is Object, then 
    a.  Let toJSON be the result of calling the [[Get]] internal method of  value with argument "toJSON". 
    b.  If IsCallable(toJSON) is true 
        i.  Let value be the result of calling the [[Call]] internal method of  toJSON passing value as the this value and with an argument list consisting of key. 

最后,日期对象已toJSON在第15.9.5.44节中定义.