While the other answers added to the prototype are completely correct, they are also a bad habit.
If you add something to the prototype, you must use Object.defineProperty() so that it does not appear as a member of the method (i.e. the for...in loop will display the elements, but not when added correctly).
Although this is not a requirement for the String prototype, it is always a bad idea to get into bad habits and then wonder why something isnβt working correctly later ...
Thus, a safe way to add a method:
Object.defineProperty(String.prototype, "strRepeater", { value: function(number) { return this.repeat(number) } };
Or be even safer:
if (!String.prototype["strRepeater"]) { Object.defineProperty(String.prototype, "strRepeater", { value: function(number) { return this.repeat(number) } }; }
In a technical note, this sets the default value enumerator: false , configurable: false and writeable: false -, which translates to "no, you cannot list me, delete me, or change me."
Object.defineProperty in MDN.
Ricochet
source share