Skip to content Skip to sidebar Skip to footer

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 app

Solution 1:

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) {
    returnthis._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 :)

Solution 2:

Alternatively, instead of creating a new variables to hold the old Storage functions you could always bind your functions like so.

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

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

And you get the benefits of representing your new functions as native code when inspected in the console as well as a less cluttered code.

Solution 3:

That is normal, you make a infinite recursion : in Storage.prototype.setItem, you call this.setItem that refers to Storage.prototype.setItem.

The same for Storage.prototype.getItem.

Post a Comment for "Overriding Default Functions In Javascript?"