Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Components.utils.import

这个方法在 Firefox 3 中被引入,它使得在不同的作用域之间分享代码变得更加容易。例如:你可以直接导入 XPCOMUtils.jsm 而不必复制/粘贴冗长的XPCOM组件。

查看 Using JavaScript code modules 了解更多细节。

Note:  Gecko 2.0  之前, JavaScript code modules 仅可以使用  file:resource: URLs. Gecko 2.0 引入了对 chrome: URLs, even those inside JAR archives 的支持。

Syntax(语法)

Components.utils.import(url [, scope]);

// Or, if you use a tool such as jslint which reports compiler errors for the above,

Components.utils["import"](url [, scope]);

Parameters(参数)

url
一个将被导入的script的URL,这个URL必须是在磁盘上的一个文件,可能在JAR之中。
scope
一个可选的导入对象,如果省略则使用全局对象。当读取文件发生错误(如语法错误等)时会抛出异常。

Example(例子)

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

Difference from mozIJSSubScriptLoader(与mozIJSSubScriptLoader的区别)

The differences from mozIJSSubScriptLoader:

  • The behavior when importing/loading the same code from different locations:
    • the subscript loader evaluates the specified code each time it is invoked, with the caller's global object.
    • Components.utils.import evaluates the code of each module only once, in its own scope.

    例如:

    var scope1 = {}, scope2 = {};
    Components.utils.import("resource://gre/modules/JSON.jsm", scope1);
    Components.utils.import("resource://gre/modules/JSON.jsm", scope2);
    assert(scope2.XPCOMUtils === scope1.XPCOMUtils);
    

    ...returns true, whereas:

    var someURL = "resource://gre/modules/JSON.jsm"; 
    var obj1 = {}, obj2 = {}; 
    var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
                           .getService(Components.interfaces.mozIJSSubScriptLoader); 
    loader.loadSubScript(someURL, obj1); 
    loader.loadSubScript(someURL, obj2);
    assert(obj2 === obj1);
    

    ...returns false.

    这意味着 Components.utils.import 更适合用于在不同的作用域JS脚本之间分享代码(数据)

Additional Resources(其他资源)

文档标签和贡献者

 此页面的贡献者: ReyCG_sub, LinusYu
 最后编辑者: ReyCG_sub,