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 contextfunc_obj- The constructor function to callargc- Number of arguments to pass to the constructorargv- Array of argument values
Returns
Returns the newly created object, orJS_EXCEPTION on error.
Example
JS_CallConstructor2
Call a JavaScript constructor with explicitnew.target support.
Parameters
ctx- The JavaScript contextfunc_obj- The constructor function to callnew_target- Thenew.targetvalue (used for class inheritance)argc- Number of argumentsargv- Array of argument values
Returns
Returns the newly created object, orJS_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
Fromexamples/point.c:
Checking Constructor Functions
JS_IsConstructor
Check if a value is a constructor function.Example
Notes
new.targetis essential for proper class inheritance in ES6 classes- When creating custom constructors, always use
new_targetto get the prototype - Constructor functions should return the newly created object
- The
JS_CALL_FLAG_CONSTRUCTORflag is set when a function is called as a constructor