Components.utils.import 编辑

Components.utils.import was introduced in Firefox 3 and is used for sharing code between different scopes easily. For example, you can import XPCOMUtils.jsm to avoid copy/pasting long XPCOM component registration boilerplate in your component files.

See Using JavaScript code modules for more details.

Note: Prior to Gecko 2.0, JavaScript code modules could only be loaded using file: or resource: URLs. Gecko 2.0 adds support for loading modules from 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
A string of the URL of the script to be loaded. The URL must point to a file on the disk, possibly in a JAR.
scope
An optional object to import onto; if omitted, the global object is used.

Under Boot2Gecko, the scope is not optional. If your code is meant to work on all platforms, you should always provide a scope.

In case of doubt, this is generally a good scope.

return value
the module's global object.
use of the return value is discouraged since it grants access to the module's internal properties which are not part of its public API.

import throws if it encounters an error (like a syntax error) in the file it reads.

Example

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

Difference from 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.

For example:

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.

This means Components.utils.import is better suited for efficient sharing of code (and data?) between JS scripts running in different scope.

Additional Resources

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:85 次

字数:4759

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文