What's the difference in using toString() compared to JSON.stringify()?

前端 未结 4 866
北荒
北荒 2020-12-08 04:28

In both the cases I get in output the content of the object:

alert(JSON.stringify(obj));

or

alert(obj.toString());
<         


        
4条回答
  •  旧巷少年郎
    2020-12-08 04:51

    As you might have noticed, while you tried (hopefully), calling .toString() which any object inherits (*) from Object.prototype.toString(), returns [object Object].

    Thats how its defined internally, returning the internal [Class] name from an object. Of course, other objects can override this method (remember, its just originally defined on the prototype chain) and return pretty much anything.

    JSON.stringify() on the other hand, is a method of the JSON object, which kind of serializes an object structure into a string version. Hence, Javascript Object Notation, it will describe an object with all nested structures in pure ascii string.


    (*) exception: objects created with Object.create(null);

提交回复
热议问题