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

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

Document Tags and Contributors

 Contributors to this page: teoli, kmaglione, gal007, wbamberg, Delapouite, kscarfone, Sheppy
 Last updated by: kmaglione,