Nuru Salihu Nuru Salihu - 1 year ago 90
Javascript Question

Rename builtin prototype method in javascript

I am asked a question today that took me by surprise . I know

repeat string to the said numbers in javascript. Example.


Should print


I was asked to do the same thing but instead using
, i should use my new method like
in such a way that.


Should equal


Please how do i do this ? Any help would be appreciated.

Answer Source

There are 3 options:

1) Creating an alias to the prototype:

String.prototype.strRepeater = String.prototype.repeat;

2) Creating a wrapper around the prototype:

String.prototype.strRepeater = function() {
  return this.repeat.apply(this, arguments);

3) Creating your own method:

String.prototype.strRepeater = function(times) {
  var res = "";
  for (var i = 0; i < times; i++) {
    res += this;
  return res;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download