Skip to main content

Custom JavaScript Classes

QuickJS allows you to attach C opaque data to JavaScript objects using the class system.

Overview

Creating a custom class involves:
  1. Allocating a class ID
  2. Defining the class with a JSClassDef
  3. Creating instances with JS_NewObjectClass()
  4. Attaching C data with JS_SetOpaque()
  5. Retrieving C data with JS_GetOpaque()

Class ID Management

JS_NewClassID

Allocate a new class ID.

Parameters

  • rt - The JavaScript runtime
  • pclass_id - Pointer to a class ID variable (will be set to the new ID)

Returns

Returns the new class ID.

Example

Class Definition

JSClassDef Structure

JSClassFinalizer

Called when an object is garbage collected.
Important: The finalizer should only release C resources. It is invalid to execute JavaScript code from it.

JSClassGCMark

Called during garbage collection to mark referenced objects.

JS_NewClass

Register a new class.

Example from point.c

Setting Up Class Prototype

JS_SetClassProto

Set the prototype for a class.

Example from point.c

JS_GetClassProto

Get the prototype for a class.

Creating Class Instances

Use JS_NewObjectClass() or JS_NewObjectProtoClass() as shown in the Object Creation page.

Opaque Data Management

JS_SetOpaque

Attach C data to an object.

Parameters

  • obj - The object (must be a custom class instance)
  • opaque - Pointer to C data

Returns

Returns 0 on success, -1 on error. Note: Only supported for custom classes.

JS_GetOpaque

Retrieve C data from an object.

Parameters

  • obj - The object
  • class_id - Expected class ID

Returns

Returns the opaque pointer, or NULL if the object is not of the specified class or if no opaque data was set.

JS_GetOpaque2

Retrieve C data with automatic exception throwing.
Returns the opaque pointer, or NULL and throws a TypeError if the object is not of the specified class.

Example from point.c

Complete Example: Point Class

From examples/point.c:

Class Utilities

JS_GetClassID

Get the class ID of an object.
Returns the class ID if v is an object, otherwise returns JS_INVALID_CLASS_ID.

JS_IsRegisteredClass

Check if a class ID is registered.

JS_GetClassName

Get the name of a registered class.
Returns the class name atom or JS_ATOM_NULL if not registered. Must be freed with JS_FreeAtom().

Notes

  • Class IDs are allocated per-runtime
  • JSClassDef structures are allocated per-runtime
  • Prototypes are set per-context with JS_SetClassProto()
  • Always use JS_GetOpaque2() in methods that need type checking
  • Finalizers run during garbage collection - don’t execute JavaScript code in them
  • Use gc_mark to tell the GC about objects referenced by your C data