問題描述
為什麼我不能在 IE8 (javascript) 上擴展 localStorage? (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?
參考解法
方法 1:
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.
(by Eric Johnson、kirilloid)