Eric Johnson
Eric Johnson

Reputation: 17978

Why can't I extend localStorage on IE8 (javascript)?

I'd like to add 2 methods to localStorage. My goal is to end up with something like this:

localStorage.setObject(key, object);
localStorage.getObject(key);

This solution works in most browsers but not IE8:

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

Storage.prototype.getObject = function(key) {
    return JSON.parse(this[key]);
}

After doing some research, apparently I could use Lawnchair.js or work around it some other way. But I'm wondering why it doesn't work in IE8. I can extend String and Array. Why not Storage? How can I find out which objects I can extend and which ones I can't extend in IE8?

Upvotes: 3

Views: 788

Answers (1)

kirilloid
kirilloid

Reputation: 14304

This is IE. You also can't extend DOM elements. If you sometimes really-really need to call a function, you can do it via Storage.prototype.getObject.call(localStorage, 'hello').

Also extending built-in objects is not considered as good thing.

Upvotes: 2

Related Questions