Overriding default functions in Javascript?

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

Background:
After finding 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 much ahead of the default localStorage.getItem and localStorage.setItem to reduce my prefix.

My example completely destroys Firefox because it calls itself recursively, so it is clearly not close to a solution. Perhaps he clarifies what I want to achieve.

The code:

 Storage.prototype.setItem = function(key, value) { this.setItem("prefix"+key, value); }; Storage.prototype.getItem = function(key, value) { return this.getItem("prefix"+key); }; 
+4
source share
3 answers

You need to keep 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 do not, you will get an infinite loop occupying the stack space at each iteration, which will lead to a stack overflow, your browser will crash :)

+10
source

Alternatively, instead of creating new variables to store old storage functions, you can always bind your functions like this.

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

And you get the benefits of presenting your new features as native code when checking in the console, as well as in less cluttered code.

+2
source

This is normal, you do infinite recursion: in Storage.prototype.setItem you call this.setItem, which refers to Storage.prototype.setItem.

Same for Storage.prototype.getItem.

0
source

Source: https://habr.com/ru/post/1396292/


All Articles