原文:http://hi.baidu.com/xletian/blog/item/406ba351e199749f8c54308d.html
XPCOM是一个跨平台的组件对象模型,类似微软COM。我们可以用javascript或C++写组件,XPCOM自身提供了一套核心组件和类,如文件和内存管理,线程,基本数据结构(string,array, variants)。
下面是一个JAVASCRIPT组件的HELLO WORLD例子。
首先在前面的HELLO WORLD扩展目录下增加目录Components,在其中新建文件helloworld.js文件,内容如下:
[code=Javascript]
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
function HelloWorld() {
this.wrappedJSObject = this;
}
HelloWorld.prototype = {
classDescription: "My Hello World Javascript XPCOM Component",
classID: Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"),
contractID: "@dietrich.ganx4.com/helloworld;1",
QueryInterface: XPCOMUtils.generateQI(),
hello: function() { return "Hello World!"; }
};
var components = [HelloWorld];
function NSGetModule(compMgr, fileSpec) {
return XPCOMUtils.generateModule(components);
}
[/code]
删除配置文件夹的compreg.dat和xpti.dat;
然后把hello world菜单的事件函数改为以下内容:
[code=javascript]
try {
// this is needed to generally allow usage of components in javascript
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var myComponent = Components.classes['@dietrich.ganx4.com/helloworld;1']
.getService().wrappedJSObject;
alert(myComponent.hello());
} catch (anError) {
dump("ERROR: " + anError);
}
[/code]
可以看到,XPCOM组件不需要用script标签引入,而是用Components对象来调用。XPCOM的更多内容见https://developer.mozilla.org/en/xpcom。
转:http://fregen.yo2.cn/articles/xpcom-basic.html
浙公网安备 33010602011771号