为什么JSON.stringify只显示click事件的isTrusted成员?

San*_*aab 7 javascript json dom-events

HTML:

<button onclick="foo(event);">Test</button>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

window.foo = function(event) {
  console.log(JSON.stringify(event));
}
Run Code Online (Sandbox Code Playgroud)

控制台结果:

{"isTrusted":true}
Run Code Online (Sandbox Code Playgroud)

它发生在Chrome上.我还没有测试过其他浏览器.

For*_*say 5

某些属性未包含在 JSON.stringify 中的原因有很多:

  1. 它们可能是functions,无法字符串化
  2. 它们可能属于对象的原型(即类),而不是直接属于对象本身。

如果您需要包含额外的数据,最好的选择是使用您想要包含的内容手动构造一个新对象:

window.foo = function(event) {
  console.log(JSON.stringify({keyCode: event.keyCode));
}
Run Code Online (Sandbox Code Playgroud)