2012-02-13 70 views
4

问题:
我可以重写JavaScript中的“默认”功能吗?在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); 
}; 

回答

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

如果你不这样做,你会得到一个无限循环在每次迭代消耗堆栈空间,从而导致堆栈溢出,崩溃浏览器:)

+5

+1栈溢出..不是无限循环 – 2012-02-13 21:54:06

+0

其两个:)无限递归导致堆栈溢出!它可能得到没有无限递归的堆栈溢出:P – caleb 2012-02-13 21:55:52

+0

是的,这是真的。但是来吧。这会因堆栈溢出而失败。它是一个无限循环,它不会产生JS错误。 – 2012-02-13 21:58:12

0

是正常的,你做一个无限循环:在Storage.prototype.setItem中,您调用引用Storage.prototype.setItem的this.setItem。

Storage.prototype.getItem相同。

2

或者,不是创建一个新的变量来保存旧的存储函数,你总是可以像你这样绑定你的函数。

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

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

而且你在控制台,以及一个更简洁的代码检查时较新的功能本地代码的好处。

+0

我用你的答案,因为它看起来像这不能被撤消,这是我想要的。真的吗? – StarQuake 2015-05-27 09:14:05

+0

据我所知,它不能。 – 2015-05-31 17:48:38