0

我在 chrome 扩展的内容脚本中使用简单的自定义类型。然后通过 chrome.extension.sendRequest() 将项目数组发送到后台页面。在 bgpage 调试器中显示我的类型的实例没有这些方法。此外,具有未定义值的类型属性也会发生同样的情况。怎么了。

function User(id, holder) {
  this.id = id;
  var hObj = {};
  hObj[holder] = 'undefined'; // this is ok
  this.holder = hObj;
  this.Result = undefined; // this will be lost
  this.Code = undefined; // this will be lost
}
// this will be lost
User.prototype.getFirstHolderType = function() {
  for (h in this.holder) {
    if (h) return h;
  }
  return false;
};
// this will be lost
User.prototype.hasHolderType = function(h_type) {
  for (h in this.holder) {
    if (h_type === h) return true;
  }
  return false;
};

//...

 chrome.extension.sendRequest({id: "users_come", users: users}, 
          function(response) {});
4

1 回答 1

0

消息传递使用JSON.stringify,它在对对象进行字符串化时从对象中删除函数。

为什么? 函数不仅仅是代码——它是一个包含大量变量/范围信息的闭包。如果一个函数使用一个全局变量并且该函数被移动到一个新的执行环境,它应该如何表现?(事实上​​,这个问题比“它应该如何表现?”更深刻,更像是“函数范围内的所有变量如何与函数一起传输?”。)

如果您想传输您的函数代码(并提前知道目的地将存在必要的变量),您可以使用toString您的成员函数来传输字符串并eval在到达时使用并重新创建它们。

JSON.stringify也会删除具有undefined值的成员。例如,JSON.stringify({"a":undefined})yield "{}"。如果您希望保留这些值,请将它们设置为null。设置为undefined的成员变量与从未设置的成员变量无法区分。)

于 2012-05-10T14:45:10.600 回答