André Selmanagić

about programming, games and tools

[Tutorial] Get rid of XPCOM syntax with JS Modules and Components.Constructor

In case you dislike the syntax of creating XPCOM components, you can use Components.Constructor to achieve a more Javascript like syntax for object-creation. Combine this with JS modules and your constructors can be accessed from everywhere.

MozXPCOM.jsm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var EXPORTED_SYMBOLS = ["MOZ"];

const Cc = Components.classes;
const Ci = Components.interfaces;
const CCtor = Components.Constructor;

var MOZ =
{
  CON: {}
};

MOZ.CON.nsLocalFile     = "@mozilla.org/file/local;1";
MOZ.LocalFile           = CCtor(MOZ.CON.nsLocalFile, Ci.nsILocalFile);

MOZ.CON.nsMutableArray  = "@mozilla.org/array;1";
MOZ.MutableArray        = CCtor(MOZ.CON.nsMutableArray, Ci.nsIMutableArray);

Usage

1
2
3
4
5
Components.utils.import("resource://myext/MozXPCOM.jsm");

// ...

var anArray = new MOZ.MutableArray();

I prefer to put all constructors in a MOZ-object, so I don’t have to export them all.

Comments