Modifying String prototype for all modules

Hi,

I’m developing an extension for Firefox, and for practical purpose I have modified the String prototype to add methods lacking in default JavaScript.

But these new methods are not recognized in modules.

Example:

String.prototype.myfunction = function (params) {
    ...
}

Then you can use this method in the current file.

"string of chars".myfunction(params)

But the prototype of String is modified only for the current file.

If you import a module with

var mymodule = require("./mymodule.js");

The code in mymodule.js can’t use these new methods for String. If I do so, it will generate an error such as:

myfunction is not a function

So, how to make modifications of the prototype String available for all imported modules?

You would have to loadSubScript the file that adds the prototype. So like this:

Services.scriptloader.loadSubScript('path to file that adds to prototype');

Here are the docs https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/mozIJSSubScriptLoader#loadSubScript()

Modules run in their own global scope, so they won’t automatically see a re-defined String from their importing scope.

One approach to your problem would be to modify your prototypes within the module, within every module if necessary. This has the advantage of being very simple for the rest of your code, and also avoids modifying the actual global which could affect other code.

Another way to go is to force all your module code to operate in whichever global namespace it happens to have been exported to. This has the advantage of picking up on things like your modified prototype without having to explicitly know about them, but obviously you’ve lost one of the primary reasons for using a module in the first place.

If you don’t need the namespacing features of a CommonJS module then you could import that code in a different way so that it is entirely in the same scope as the importing script.

Thanks. I finally modified String prototype for each module where it’s necessary.