Skip to main content

Object Creation

QuickJS provides several functions to create JavaScript objects from C code.

JS_NewObject

Create a new plain JavaScript object.

Parameters

  • ctx - The JavaScript context

Returns

Returns a new empty object.

Example

JS_NewObjectProto

Create a new object with a specific prototype.

Parameters

  • ctx - The JavaScript context
  • proto - The prototype object (can be JS_NULL for null prototype)

Returns

Returns a new object with the specified prototype.

Example

JS_NewObjectClass

Create a new object instance of a custom class.

Parameters

  • ctx - The JavaScript context
  • class_id - The class ID of the object to create

Returns

Returns a new object of the specified class.

Example

JS_NewObjectProtoClass

Create a new object with both a specific prototype and class.

Parameters

  • ctx - The JavaScript context
  • proto - The prototype object
  • class_id - The class ID

Returns

Returns a new object with the specified prototype and class.

Example

From examples/point.c:

JS_NewObjectFrom

Create an object from arrays of atoms and values.

Parameters

  • ctx - The JavaScript context
  • count - Number of properties
  • props - Array of property name atoms
  • values - Array of property values (ownership transferred)

Returns

Returns a new object with the specified properties.

JS_NewObjectFromStr

Create an object from arrays of string property names and values.

Parameters

  • ctx - The JavaScript context
  • count - Number of properties
  • props - Array of property name strings
  • values - Array of property values (ownership transferred)

Returns

Returns a new object with the specified properties.

Example

JS_ToObject

Convert a value to an object.

Parameters

  • ctx - The JavaScript context
  • val - The value to convert

Returns

Returns an object representation of the value, or JS_EXCEPTION on error.

Example

Notes

  • All JS_NewObject* functions return values that must be freed with JS_FreeValue()
  • For custom classes, use JS_NewObjectClass() or JS_NewObjectProtoClass()
  • JS_NewObjectFrom* functions take ownership of the values array
  • Use JS_SetOpaque() to attach C data to class objects