#include "jsapi.h" // Create a new JSObject JS::RootedObject newObj(aJSContext, JS_NewObject(aJSContext, nullptr)); // Set a property on the object JS_DefineProperty(aJSContext, newObj, "name", "Alice", JSPROP_PERMANENT | JSPROP_ENUMERATE); // Access the property JS::RootedValue nameVal(aJSContext); if (!JS_GetProperty(aJSContext, newObj, "name", &nameVal)) { // Handle failure condition } std::string name = JS_EncodeStringToUTF8(aJSContext, JS::ToString(nameVal));
#include "jsapi.h" // Define a JavaScript function within an object JS::RootedObject myObj(aJSContext, JS_NewObject(aJSContext, nullptr)); JS_DefineFunction(aJSContext, myObj, "greet", [](JSContext* cx, unsigned argc, JS::Value* vp){ JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (args.length() != 1) { JS_ReportError(cx, "greet() expects one argument"); return false; } std::string name = JS_EncodeStringToUTF8(cx, args.get(0).toString()); printf("Hello, %s!\n", name.c_str()); args.rval().setUndefined(); return true; }); // Call the function from C++ JS::RootedValue ret(aJSContext); JS::RootedValue arg(aJSContext, JS::StringHandle(JS_NewStringCopyZ(aJSContext, "Alice"))); if (!JS_CallFunctionName(aJSContext, myObj, "greet", JS::HandleValueArray::fromMarkedLocation(1, &arg), &ret)) { // Handle failure condition }This example demonstrates how to define a JavaScript function within an object using cpp JSObject, and then how to call that function from C++.