简体   繁体   中英

javascript/jQuery storing object in cookie and retrieve

I've seen lots of questions about a similar issues as mine but not entirely answering my question.

My issue is that I need to store an entire instance of an object, that means that besides his fields, I need also its related methods.

My code:

storing object :

$.cookie(key, JSON.stringify(value), { expires: expire });

retrieve object :

var value = $.cookie(key); if (value === null || value === undefined) { return value = ""; } return JSON.parse(value);

The objects I get from the cookies have their fields, but the object doesnt have the methods that I attached prior to the storing.

Just so you guys/ladies can understand what object im trying to work with, i provided the following fiddle : https://jsfiddle.net/5hhgtnxh/

You simply can't save methods or functions to cookie or local storage without some hacks, JSON.stringify will omit keys with functions keeping only data. And is this neccessary to save methods? They're in code already. You could split your object on data and methods, saving only data to cookie/localstorage.

By the way, since JSON is not for Javascript, but for passing data between different systems or component, it just doesn't allow functions as values. See http://json.org/ for detailed format spec.

Really simple example:

var CustomObject = function (data) {
  var data = data;
  this.getX = function () {
    return data.x;
  };
  this.setX = function (x) {
    data.x = x;
  };
  this.getData = function () {
    return data;
  };
};

var o = new CustomObject({});
o.setX(42);
$.cookie('myObj', JSON.stringify(o.getData()));

//later, let's initialize obj from cookie

var custData = $.cookie('myObj');
var o2 = new CustomObject(custData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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