覆盖Javascript中的默认函数? [英] Overriding default functions in Javascript?

查看:67
本文介绍了覆盖Javascript中的默认函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我可以覆盖Javascript中的默认功能吗?

Question:
Can I override "default" functions in Javascript?

背景:

在确定我在 localStorage 中存储的对象之间发生冲突之后,我决定应该为所有键应用前缀以避免冲突。显然,我可以创建一个包装函数,但它会更加整洁,以覆盖默认的 localStorage.getItem & localStorage.setItem 直接将我的前缀记入帐户。

Background:
After figuring out that I had collisions between objects stored in localStorage, I decided that I should apply a prefix to all keys to avoid collisions. Obviously, I could create a wrapper function, but it would be so much neater to override the default localStorage.getItem & localStorage.setItem directly to take my prefix into account.

我的例子完全杀死了Firefox,因为它递归调用自身,所以它显然不是一个解决方案。也许它澄清了我想要完成的任务。

My example kills Firefox completely as it recursively calls itself, so it clearly isn't close to a solution. Perhaps it clarifies what I want to accomplish though.

代码:

Storage.prototype.setItem = function(key, value) {
    this.setItem("prefix"+key, value);
};

Storage.prototype.getItem = function(key, value) {
    return this.getItem("prefix"+key);
};


推荐答案

您需要存储旧函数。

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

如果不这样做,每次迭代都会产生无限循环消耗堆栈空间,从而导致堆栈溢出,导致浏览器崩溃:)

If you don't, you get an infinite loop consuming stack space at every iteration, resulting in a stack overflow, crashing your browser :)

这篇关于覆盖Javascript中的默认函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆