繁体   English   中英

从IndexedDB检索类型化对象

[英]Retrieved typed objects from IndexedDB

在IndexedDB中存储和检索类型化Javascript对象的最有效方法是什么?

问题在于IndexedDB不存储原型信息,因此您只能存储和检索普通对象(或数组或基元或其他一些类型)。 __proto__一种解决方法是为从数据库中检索的对象显式分配__proto__ 例如,要获得一个Game对象

game.__proto__ = Game.prototype;

但是, __proto__分配存在以下问题:A)尽管在实践中受支持,但在技术上是非标准的,并且B)对代码进行了优化。 实际上,Firefox给出了明确的警告

更改对象的[[Prototype]]将导致您的代码运行非常缓慢; 而是使用Object.create创建具有正确的初始[[Prototype]]值的对象

显然, Object.create在这里是不可能的。 __proto__赋值还有其他更好的选择吗?

您可以考虑仅存储后备数据对象本身。 游戏将成为可存储对象的代理。

function Game(props) {
  this.props = props || {};
}

// An example of property decoration
Game.prototype.set x(value) {
  this.props.x = value;
};
Game.prototype.get x() {
  return this.props.x;
};

// Use this when initializing a game after retrieving game data from indexedDB store. 
// e.g. when creating a new game, use var newGame = Game.fromSerializable(props);
Game.fromSerializable = function(props) {
  return new Game(props);
};

// When it comes time to persist the game object, expose the serializable props object
// so that the caller can pass it to store.put/store.add
Game.prototype.toSerializable = function() {
  return this.props;
};

这可能比麻烦处理可以通过indexedDB用于读取/写入的结构化克隆算法传递的信息要简单,或者比使用其他人可能难以理解的奇怪的一次性黑客更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM