为何Reflect.defineProperty定义的属性无法被JSON.stringify序列化?
问题原因解析
先看你的代码:
let foo = {}; Reflect.defineProperty(foo,'bar',{value:1}); console.log(foo); // { bar: 1 } console.log(JSON.stringify(foo)); // { }
核心原因很简单:
- 通过
Reflect.defineProperty(包括Object.defineProperty)添加属性时,默认情况下属性是不可枚举的 JSON.stringify只会序列化对象的可枚举自有属性,所以不可枚举的bar会被跳过
你可以用Object.keys(foo)验证这一点,执行后会返回空数组,说明bar确实不可枚举。
如果想要让bar被JSON.stringify序列化,只需要在定义属性时显式设置enumerable: true:
let foo = {}; Reflect.defineProperty(foo,'bar',{value:1, enumerable: true}); console.log(JSON.stringify(foo)); // { "bar": 1 }
补充个小知识点:直接给对象赋值(比如foo.bar = 1)时,属性的enumerable、writable、configurable默认都是true,所以这种方式加的属性能被正常序列化。
内容的提问来源于stack exchange,提问作者BuddyJoe
相关产品推荐
相关产品推荐

