【问题标题】:save methods with localStorage使用 localStorage 保存方法
【发布时间】:2014-03-09 07:36:56
【问题描述】:

我不知道如何存储包含方法的对象。如果我使用 localStorage.setItem('inventory', JSON.stringify(hero.inventory));

并且库存中的一些项目(对象)有方法,我只获取属性 hero.inventory = JSON.parse(localStorage.getItem('inventory'));

如何在不出现循环错误的情况下存储和检索对象及其所有属性和方法?

【问题讨论】:

  • 你应该只存储值而不是方法。

标签: javascript json html


【解决方案1】:

简答:你不能。

更长的答案: 您只能将字符串存储在localStorage 中。这就是您首先使用JSON.stringify()JSON.parse() 的原因。

请参阅 How to serialize & deserialize Javascript objects? 了解规避此问题的方法。

或者您的对象可以包含一个构造函数/方法,如果给定所有非方法属性,它将使用所有方法重构整个对象。

非常基本的例子:

function Countdown( start ) {
  this.start = start;
  this.ticksCounted = 0;
}

Countdown.prototype.tick = function(){
  this.start -= 1;
  this.ticksCounted += 1;
}

Countdown.parse = function( param ) {
  // get a basic object
  var result = new Countdown();

  // append all values
  for( var key in param ) {
    if( param.hasOwnProperty( key ) ) {
      result[ key ] = param[ key ];
    }
  }

  // return result
  return result;
}

以及各自的(反)序列化:

var c1 = new Countdown( 10 );
c1.tick();

console.log( c1 );

var s = JSON.stringify( c1 );

console.log( s );

var c2 = Countdown.parse( JSON.parse( s ) );

console.log( c2 );

【讨论】:

  • 非常感谢,尽管有一个错误。应该是c1.parse( JSON.parse( s ) );
  • @user3065579 这个错误更可能出现在Countdown的定义中。 parse 方法不应该在原型上。我认为将它附加到构造函数本身比附加到它的原型更干净。
猜你喜欢
  • 2016-08-27
  • 2021-12-26
  • 2016-09-08
  • 2013-11-25
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
相关资源
最近更新 更多