Rename inline prototype method in javascript

Today I am asked a question that took me by surprise. I know string.repeat(number) repeat a string to the specified numbers in javascript. Example.

 "Father".repeat(3) 

Must print

Fatherfatherfather

I was asked to do the same, but instead, using .repeat , I have to use my new method, for example strRepeater so that.

 "Father".strRepeater(3) 

Must be equal

 "Father".repeat(3); 

How can I do it? Any help would be appreciated.

+8
javascript
source share
3 answers

There are 3 options:

  • Creating an alias for the prototype:

     String.prototype.strRepeater = String.prototype.repeat; 
  • Creating a wrapper around the prototype:

     String.prototype.strRepeater = function() { return this.repeat.apply(this, arguments); }; 
  • Creating your own method:

     String.prototype.strRepeater = function(times) { var res = ""; for (var i = 0; i < times; i++) { res += this; } return res; }; 
+13
source share

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.

+6
source share

Try the following:

 String.prototype.strRepeater = function(number) { return this.repeat(number) }; console.log("Father".strRepeater(3)); 

Explanations:

  • String.prototype.strRepeater add your function to a String object
  • this.repeat(number) will call a repeated inline function with your current line in this with a number like param
  • return returns the result .repeat() outside strRepeater()
+5
source share

All Articles