0

I need a way to assign functions to object that then will be stored in the localstorage. I tryed the code below, but I get: "Uncaught TypeError: mydog.woof is not a function"

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}


var Dog = function(name) {
  this.name = name
}

Dog.prototype.woof = function woof() {
  console.log('woof woof, I am ' + this.name);
}

// Instantinate your objects with `new` keyword
var dog = new Dog('Lovely')
dog.woof()

//Store in the localstorage
localStorage.setObject('mydog', dog); 

//Get from the localstorage
var mydog = localStorage.getObject('mydog');
mydog.woof();
xRobot
  • 25,579
  • 69
  • 184
  • 304
  • localStorage can only store strings [Storing Objects in HTML5 localStorage](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – Justinas Jan 27 '17 at 08:08
  • @Justinas Yes I know, So how can I assign functions to an object that will be stored in the localstorage ? – xRobot Jan 27 '17 at 08:10

1 Answers1

3

I need a way to assign functions to object that then will be stored in the localstorage.

Web storage only stores strings.

Your best bet is to solve the problem another way, perhaps store a key that you use to look up the function in an object in your script code.

Or, given your Dog example, usually what I do in those cases is have a function associated with Dog (or even the Dog constructor) that accepts a plain object version of a dog and creates a Dog version initialized with that data. E.g., roughly:

Dog.fromPlainObject = function(plain) {
    var d = new Dog();
    Object.keys(plain).forEach(function(key) {
        d[key] = plain[key];
    });
    return d;
};

...or any of a dozen variations on that theme.

You could store the string version of the function then reconstitute it via eval, but I really wouldn't. Use storage for data, not code.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875