1

Take for example this "StartsWith" extension:

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

If I was writing a web app, I would stick that code in an ExtensionMethods.js page that I imported on a web page within my site.

But what about the case of using this on the server with Node.js?

Thanks!

Matt Cashatt
  • 23,490
  • 28
  • 78
  • 111

1 Answers1

2

Since String is globally available, it can be placed in any file that gets required. When a file gets required, it gets executed.

You don't even need to export anything.

Pascal Belloncle
  • 11,184
  • 3
  • 56
  • 56
  • Nice! So I guess the same holds true with, `Array`, `Object`, etc? – Matt Cashatt Mar 08 '13 at 02:57
  • 1
    @MatthewPatrickCashatt Also, see [this question](http://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) for some reasons why you might not want to extend a native object. Consider what might happen if your code and some module extend String#startsWith in different ways (e.g. different functionality). – Joseph Yaduvanshi Mar 08 '13 at 03:12
  • 1
    @JimSchubert--OK, after reading that post I certainly see your point. Since extension methods are so darn convenient, however, I would still like to use them responsibly--especially since it will be running on my own isolated server. SO--am I correct in thinking that as long as I name the extension methods in a way that is HIGHLY unlikely to be duplicated then I should be okay? Ex: `.stinkyBritches_startsWith()` – Matt Cashatt Mar 08 '13 at 03:35