0

I was recently looking into Javascript prototypes and how they work. Therefore, I stumbled upon the following code:

String.prototype.repeatify = String.prototype.repeatify || function(times){
    var str = '';
    for(var i = 0; i < times; i++){
        str += this;
    }
    return str;
}

alert("hello".repeatify(5));

Now I understand every aspect of how this works and why it is done this way, what I am not understanding is what or which circumstances deem this approach not recommendable, not correct or what about this should I be aware that could be a potential problem.

For your information, I already looked into other StackOverflow questions regarding this subject, but none of the answers given where clear to me, I hope it is alright if the community can answer based of the above code snippet and expand from there.

EDIT:

For future reference, readers also refer to: Extending native builtins

AGE
  • 3,752
  • 3
  • 38
  • 60
  • 1
    Changing object prototypes essentially at random can break both existing functionality and functionality that *also* modifies prototypes. See things like http://stackoverflow.com/q/8859828/438992, https://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/, and so on. – Dave Newton Jun 18 '15 at 17:11
  • 1
    The biggest problem I see with overloading common library functions is code clarity. Whenever someone who is scanning over the code sees repeatify() in use, they are likely to miss that you have redefined the functionality and arguments, and are liable to expect it to behave normally, not how you've defined it. – Blake Yarbrough Jun 18 '15 at 17:11
  • So if it was your choice to write code in this matter, would you recommend it or would you avoid it completely? If you would not avoid it then why is it 'ok' to just run with code that is likely to create a problem in the future? – AGE Jun 18 '15 at 17:13
  • 1
    I would definitely define another function, with a different name, that does what your repeatify(int x) function does. Call the other function instead. – Blake Yarbrough Jun 18 '15 at 17:15
  • 1
    http://perfectionkills.com/extending-native-builtins/ – Bergi Jun 18 '15 at 17:21
  • Feel free to submit that article as the answer with your own comments @Bergi, its amazing – AGE Jun 18 '15 at 17:29

0 Answers0