Components.utils.createObjectIn 编辑

Components.utils.createObjectIn creates a new JavaScript object in the scope of the specified object's compartment.

This function is made available as a global in sandboxes which have the wantExportHelpers option set in the Sandbox() constructor.

Note that this function is now mostly obsolete when you are using Sandbox, because you can create an object in a different compartment using new. For example, to create a new object in the compartment identified by contentWindow:

var newObject = new contentWindow.Object();

But it is really needeed from Firefox 30 onwards when trying to manipulate the DOM window. See details in https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/.

Syntax

var newObject = Components.utils.createObjectIn(obj, options);

Parameters

obj
An object indicating the compartment in which the new object should be created; the new object will be created in the scope of this object's compartment.
options
An object containing a single option defineAs, which determines the name of the object in the target compartment.

Return value

A new object in the specified scope.

Example

To create a new object in the scope of a specified DOM window, you can simply do:

function genPropDesc(value) {
  return {
    enumerable: true, configurable: true, writable: true, value: value
  };
}

var myObject = Components.utils.createObjectIn(myWindow);

var propList = {
  name: genPropDesc("name"),
  date: genPropDesc("date"),
  id: genPropDesc("id"),
  func: genPropDesc(function() { alert("Called func!"); })
};

Object.defineProperties(myObject, propList);
Components.utils.makeObjectPropsNormal(myObject);

This sets up the new object in the scope of the object myWindow, then adds properties by calling Object.defineProperties(), then normalizes them by calling Components.utils.makeObjectPropsNormal().

To create an object with a specified name, use defineAs:

var foo = Components.utils.createObjectIn(myWindow, {defineAs: "foo"});

Now the target compartment's window has a new global object named foo.

See also

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

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

发布评论

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

词条统计

浏览:104 次

字数:3880

最后编辑:7年前

编辑次数:0 次

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