Question

So in Firefox extensions it's encouraged for your extension's objects to live in sub-objects like com.contoso.myExtension . That way you have not put any objects in the global namespace and extensions generally stay out of each other's hair. (At least in the common browser.xul window)

But from what I have understand about Javascript code modules (JSMs), is that while the module itself is working in a separate namespace, the symbols that it exports will end up in the global namespace of whatever code imports it. Furthermore, it's impossible for an extension to be "nice" and only try to build sub-objects; those exported symbols will just whack whatever global variables already existed. Also you can't export a symbol like com.contoso.myExtension. It's only a simple global variable.

So what's the protocol for playing nice when using JSMs? Just make really long variable names and hope they won't collide?

Was it helpful?

Solution

First off, I haven't seen a hard a true standard for how to handle this. But we can definitely do much better than just long variable names...

You are correct about the Javascript Code Modules living in a separate namespace (so to speak), however when you import them, you don't have to import them into the global namespace. If you look at the Components.utils.import documentation, you see that you can import onto a specific scope. That is, you don't have to pollute the global namespace at all.

You can collect your modules into a myExtension namespace.

var myExtension = {};
Components.utils.import("resource://.../module.jsm", myExtension);

And wrapping this inside a self-executing function doesn't let any variables leak into the global namespace, not even myExtension!

(function(){
    var myExtension = {};
    Components.utils.import("resource://.../module.jsm", myExtension);
})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top