Skip to main content

Calling JavaScript Functions

QuickJS provides functions to call JavaScript functions and methods from C code.

JS_Call

Call a JavaScript function.
JSValue JS_Call(JSContext *ctx, JSValueConst func_obj,
                JSValueConst this_obj, int argc, JSValueConst *argv);

Parameters

  • ctx - The JavaScript context
  • func_obj - The function object to call
  • this_obj - The this value for the function call
  • argc - Number of arguments
  • argv - Array of argument values

Returns

Returns the result of the function call, or JS_EXCEPTION on error.

Example

JSValue global = JS_GetGlobalObject(ctx);
JSValue func = JS_GetPropertyStr(ctx, global, "myFunction");

JSValue args[2];
args[0] = JS_NewInt32(ctx, 42);
args[1] = JS_NewString(ctx, "hello");

JSValue result = JS_Call(ctx, func, global, 2, args);
if (JS_IsException(result)) {
    js_std_dump_error(ctx);
}

JS_FreeValue(ctx, result);
JS_FreeValue(ctx, args[0]);
JS_FreeValue(ctx, args[1]);
JS_FreeValue(ctx, func);
JS_FreeValue(ctx, global);

JS_Invoke

Invoke a method on an object by property name.
JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom,
                  int argc, JSValueConst *argv);

Parameters

  • ctx - The JavaScript context
  • this_val - The object to invoke the method on
  • atom - The atom representing the method name
  • argc - Number of arguments
  • argv - Array of argument values

Returns

Returns the result of the method call, or JS_EXCEPTION on error.

Example

JSValue obj = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, obj, "toString", JS_NewCFunction(ctx, my_toString, "toString", 0));

JSAtom atom = JS_NewAtom(ctx, "toString");
JSValue result = JS_Invoke(ctx, obj, atom, 0, NULL);
JS_FreeAtom(ctx, atom);

if (!JS_IsException(result)) {
    const char *str = JS_ToCString(ctx, result);
    printf("%s\n", str);
    JS_FreeCString(ctx, str);
}

JS_FreeValue(ctx, result);
JS_FreeValue(ctx, obj);

Notes

  • Both functions transfer ownership of argument values to the callee
  • The returned value must be freed with JS_FreeValue()
  • Always check for JS_EXCEPTION before using the result
  • JS_Invoke() is a convenience function that combines property lookup and function call

Build docs developers (and LLMs) love