js::Compartment* compartment = new js::Compartment(); JSContext* context = compartment->getContext(); JS::RootedValue result(context); const char* expression = "2 + 2"; if (JS::Evaluate(context, JS::CompileScript(context, expression), &result)) { if (result.isNumber()) { int intValue = (int) result.toNumber(); std::cout << "Result: " << intValue << std::endl; } }
js::Compartment* compartment = new js::Compartment(); JSContext* context = compartment->getContext(); JS::RootedValue result(context); const char* script = "function add(a, b) { return a + b; }"; JS::CompileScript(context, script); JS::RootedObject global(context, JS::CurrentGlobalOrNull(context)); JS::RootedString functionName(context, JS_NewStringCopyZ(context, "add")); JS::RootedValue functionValue(context); if (JS_GetProperty(context, global, functionName, &functionValue)) { JS::RootedObject function(context, &functionValue.toObject()); JS::RootedValue arguments(context); JS::RootedValue returnValue(context); JS::AutoValueArray<2> args(context); args[0].setInt32(2); args[1].setInt32(3); if (JS_CallFunctionValue(context, global, function, args, &returnValue)) { if (returnValue.isNumber()) { int intValue = (int) returnValue.toNumber(); std::cout << "Result: " << intValue << std::endl; } } }The JSScript compartment is a part of SpiderMonkey, which is the JavaScript engine used in Firefox. Therefore, it can be considered as a package/library belonging to the Mozilla organization.