Skip to main content

Constructor Functions

QuickJS provides functions to invoke JavaScript constructors from C code.

JS_CallConstructor

Call a JavaScript constructor to create a new object.

Parameters

  • ctx - The JavaScript context
  • func_obj - The constructor function to call
  • argc - Number of arguments to pass to the constructor
  • argv - Array of argument values

Returns

Returns the newly created object, or JS_EXCEPTION on error.

Example

JS_CallConstructor2

Call a JavaScript constructor with explicit new.target support.

Parameters

  • ctx - The JavaScript context
  • func_obj - The constructor function to call
  • new_target - The new.target value (used for class inheritance)
  • argc - Number of arguments
  • argv - Array of argument values

Returns

Returns the newly created object, or JS_EXCEPTION on error.

Example from point.c

Creating Constructor Functions

JS_SetConstructorBit

Mark a function as a constructor.

JS_SetConstructor

Set up the bidirectional link between a constructor and its prototype.

Example

From examples/point.c:

Checking Constructor Functions

JS_IsConstructor

Check if a value is a constructor function.

Example

Notes

  • new.target is essential for proper class inheritance in ES6 classes
  • When creating custom constructors, always use new_target to get the prototype
  • Constructor functions should return the newly created object
  • The JS_CALL_FLAG_CONSTRUCTOR flag is set when a function is called as a constructor