Ind*_*ial 4 javascript local-storage
问题:
我可以在Javascript中覆盖"默认"功能吗?
背景:
在确定我存储的对象之间发生了冲突之后localStorage,我决定应该为所有键应用前缀以避免冲突.显然,我可以创建一个包装器函数,但它会更加整洁地覆盖默认值localStorage.getItem并localStorage.setItem直接考虑我的前缀.
我的例子完全杀死Firefox,因为它递归调用自己,所以它显然不是一个解决方案.也许它澄清了我想要完成的事情.
码:
Storage.prototype.setItem = function(key, value) {
this.setItem("prefix"+key, value);
};
Storage.prototype.getItem = function(key, value) {
return this.getItem("prefix"+key);
};
Run Code Online (Sandbox Code Playgroud)
cal*_*leb 10
您需要存储旧功能.
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value) {
this._setItem("prefix" + key, value);
};
Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype.getItem = function(key) {
return this._getItem("prefix" + key);
};
Run Code Online (Sandbox Code Playgroud)
如果不这样做,每次迭代都会产生无限循环消耗堆栈空间,从而导致堆栈溢出,导致浏览器崩溃:)
| 归档时间: |
|
| 查看次数: |
2101 次 |
| 最近记录: |