JSON.stringify不返回预期的对象

Ste*_*vie 0 javascript json websocket

我最近一直在玩Node.js和Websockets.我正在那里,但是有一个关于JSON.stringify(客户端)的奇怪问题.

我喜欢使用JSON.stringify来确定服务器返回的对象属性.

例如,我有以下代码片段:

ws.onmessage = function(param1) {
    alert(JSON.stringify(param1));
}
Run Code Online (Sandbox Code Playgroud)

这会显示一个警告框 {"isTrusted" : true}

由于这个输出,我以为我的服务器没有将消息发送回客户端.出于好奇,我决定只修改警报功能

alert(param1.data);

预期的消息就在那里!所以我的问题是为什么data当JSON.stringify 显然没有包含一个对象时呢?

T.J*_*der 7

JSON.stringify仅包括输出中对象的自身可枚举属性; 这由规范中的抽象SerializeJSONObject操作涵盖.这意味着遗漏了属性和非可枚举属性.

显然,您邮件中唯一拥有的,可枚举的属性是isTrusted.

无偿的例子:

function Thingy(name, age) {
  // Save `name` as an own, enumerable property
  this.name = name;
  
  // Save `age` as an own, non-enumerable property
  Object.defineProperty(this, "age", {
    value: age
  });
}

// Define `what` as a property that will be inherited by
// all `Thingy` instances:
Thingy.prototype.what = "evs";

// Create one
var t = new Thingy("foo", 42);

// Get the JSON for it:
console.log(JSON.stringify(t)); // {"name":"foo"}
Run Code Online (Sandbox Code Playgroud)


不过,这里的外卖消息是alert2016年几乎没有适合调整风格的地方.不要在黑暗中使用alert(或console.log)手电筒绊倒,而是使用功能强大,功能齐全的调试器打开灯光进入浏览器:在处理程序的第一个语句上放置一个断点,当达到断点时,检查param1动态的内容.它将显示自己的属性和继承的属性,可枚举的属性和不可枚举的属性,以及暂停JavaScript代码的当前值.