JSObject * JS_NewObject(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); JSObject * JS_NewObjectWithGivenProto(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent);
||The context in which to create the new object. Requires request. In a
||Pointer to the class to use for the new object. If this is
Pointer to the prototype object to use for the new object. The new object will inherit all of the prototype object's properties and methods, and the new object's
||Pointer to the parent of the new object. The new object's
JS_NewObject creates a new object based on a specified class, prototype, and parent object.
cx is a pointer to a context associated with the runtime in which to establish the new object.
clasp is a pointer to an existing class to use for internal methods, such as
proto is an optional pointer to the prototype object with which to associate the new object.
JS_NewObject attempts to assign the new object the prototype object belonging to
clasp, if one is defined there. Otherwise, it creates an empty object stub for the prototype.
parent is an optional pointer to an existing object to which to set the new object's parent object property. You can set parent to
NULL if you do not want to set the
__parent__ property. See JS_GetParent for details on what the parent property does.
JS_NewObject returns a pointer to the new object. Otherwise it returns
JS_NewObjectWithGivenProto behaves exactly the same, except that if
NULL, it creates an object with no prototype.
Starting with Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), you can create a new object in a specific compartment using the
Choosing a default prototype
Like many JSAPI functions, JS_NewObject selects an appropriate prototype for the newly created object if you don't supply one yourself. In each case, the choice is driven by the new object's class (here,
clasp), its parent scope (here,
parent), and perhaps the context (here,
cx). Roughly speaking, we use the parent or the context to find a global object, find the given class's constructor in that global object, and then use that constructor's prototype.
Here's how the process works in detail:
First, we must identify a global object. If the parent is non-NULL, we assume it is part of a scope chain, walk to the end of that chain, and use the global object we find there. If the parent is NULL, we use the global object at the end of the scope chain in which the context is currently executing. In other words, the context's current scope acts as a default parent. If the context is not currently executing any code, we use
JS_GetGlobalObject to find a global object associated with the context.
Finally, we must find a prototype. If the constructor has a
prototype property, we use its value. Otherwise, we use
Object.prototype, looking up the constructor for
Object as described above.