2

I recently came across the idea that it would be great(/easy/convenient) to define dynamic properties on the Javascript String prototype, so you can use your string literals and variables kinda like it works in ruby. Take this example:

// Using ES2015 syntax features
Object.defineProperty(String.prototype, 'ucFirst', {
  get() {
    return this.charAt(0).toUpperCase() + this.substr(1);
  }
});

This way you'd be able to use your strings like this:

"foo".ucFirst                        // "Foo"
"lorem ipsum dolor sit amet".ucFirst // "Lorem ipsum dolor sit amet"
$t('some_i18nized_string').ucFirst   // You get it

I can already imagine a whole bunch of handy applications for that, but I am not sure about it. It works, but I am kinda afraid that it might be bad practice and it kinda smells funny.

Let me know what you think about it.

George Kagan
  • 5,913
  • 8
  • 46
  • 50
sebwas
  • 99
  • 1
  • 8
  • Sure, it's considered to be a bad practice, but if you're absolutely certain this isn't going to cause issues in your application, I don't see why not. – Cerbrus Nov 07 '16 at 13:07
  • 1
    Extending native prototypes is always bad practice, but people seem to do it all the time anyway. What's wrong with `ucFirst("foo")` instead – adeneo Nov 07 '16 at 13:09
  • This is largely dealt with in [this question](http://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice). Yes, it's more possible than it has ever been previously, but the possibility for conflicts with other code is enormous. – lonesomeday Nov 07 '16 at 13:10
  • This is a matter of opinion, and so off-topic for SO. If you decide to do it, [my answer here](http://stackoverflow.com/a/6394872/157247) notes a few pitfalls to avoid. – T.J. Crowder Nov 07 '16 at 13:11
  • @adeneo: Polluting the global scope. Bad practice! Basically, whatever you're happy with, imo. – Cerbrus Nov 07 '16 at 13:11
  • Thank you for your answers. @lonesomeday: thanks for pointing that out. In my previous research I did not find this question. – sebwas Nov 07 '16 at 13:19
  • adeneo: imo this kinda breaks the readability. When you use a whole bunch of simple modifiers you'd rather want to chain them, instead of calling each of the functions explicitly. Also this limits its use to Strings only (which really is the only place where this should work anyway) -- T.J.Crowder: thanks for the link. However, how is that off-topic here? Isn't this a forum for (among other things) discussion (although I see how this is a largely opinion-based topic) – sebwas Nov 07 '16 at 13:25
  • @sebwas: Glad that helped! No, SO is very focussed on *not* being a discussion forum. More in the help: [*What types of questions should I avoid asking?*](/help/dont-ask), [*What topics can I ask about here?*](/help/on-topic) – T.J. Crowder Nov 07 '16 at 13:43

0 Answers0