Why doesn't JSON.stringify display object properties that are functions?

前端 未结 3 1374
盖世英雄少女心
盖世英雄少女心 2020-12-16 03:28

Why doesn\'t JSON.stringify() display prop2?

var newObj = {
  prop1: true,
  prop2: function(){
    return \"hello\";
  },
  prop3: false
};

alert( JSON.str         


        
3条回答
  •  眼角桃花
    2020-12-16 04:26

    It's not supposed to stringify methods (or any functions) - especially since most methods of built in objects (and thus the prototypes of any user-defined objects) are native code.

    If you really need it to print your methods out, you can override your object's .toString method, but when you call JSON.parse on the stringified output, it will treat the method as if it were just a string, and to be able to call it as a function you'd have to eval it - a practice that is typically not recommended.

提交回复
热议问题