2012-02-13 71 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