Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding default functions in Javascript?

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

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.

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.

Code:

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

Storage.prototype.getItem = function(key, value) {
    return this.getItem("prefix"+key);
};
like image 293
Industrial Avatar asked Dec 12 '22 05:12

Industrial


1 Answers

You need to store the old function.

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 :)

like image 118
caleb Avatar answered Dec 14 '22 19:12

caleb