Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename builtin prototype method in javascript

Tags:

javascript

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

"Father".repeat(3)

Should print

FatherFatherFather

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

"Father".strRepeater(3)

Should equal

"Father".repeat(3);

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

like image 828
Nuru Salihu Avatar asked Oct 26 '16 01:10

Nuru Salihu


3 Answers

While the other answers adding to the prototype are completely correct, they're also a bad habit to get into.

If adding anything to a prototype you should be using Object.defineProperty() so it doesn't appear as a member of the method (ie, a for...in loop will show up members, but not when added properly).

While this isn't a requirement for the String prototype, it's always a bad idea to get into bad habits and then wonder why things aren't working correctly later...

So the safe way to add the method is:

Object.defineProperty(String.prototype, "strRepeater", {
    value: function(number) {
        return this.repeat(number)
    }
};

Or to be even more safe:

if (!String.prototype["strRepeater"]) {
    Object.defineProperty(String.prototype, "strRepeater", {
        value: function(number) {
            return this.repeat(number)
        }
    };
}

On a technical note, this sets it with the defaults of enumerator: false, configurable: false and writeable: false - which translates to "no, you can't list me, delete me, or change me".

Object.defineProperty on MDN.

like image 124
Rycochet Avatar answered Oct 19 '22 04:10

Rycochet


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;
    };
    
like image 28
nem035 Avatar answered Oct 19 '22 05:10

nem035


Try this:

String.prototype.strRepeater = function(number) {
  return this.repeat(number)
};

console.log("Father".strRepeater(3));

Explanations:

  • String.prototype.strRepeater add your function to the String object
  • this.repeat(number) will call the repeat built-in function with your current string inthis with number as param
  • return returns the result of .repeat() outside strRepeater()
like image 5
antoni Avatar answered Oct 19 '22 03:10

antoni