xRobot
xRobot

Reputation: 26565

How to assign function to stored object?

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();

Upvotes: 0

Views: 41

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

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.

Upvotes: 3

Related Questions