JSAPI
判断类型
JS::RootedValue v(cx, ComputeSomeValue());
bool isString = v.isString();
bool isNumber = v.isNumber();
bool isInt32 = v.isInt32(); // NOTE: internal representation, not numeric value
bool isNull = v.isNull();
bool isBoolean = v.isBoolean();
bool isObject = v.isObject(); // NOTE: not broken like typeof === “object” is :-)
赋值
JS::RootedValue v(cx);
JS::RootedString someString(cx, …);
v.setInt32(0); // or: v = JS::Int32Value(0);
v.setDouble(0.5); // or: v = JS::DoubleValue(0.5);
v.setString(someString); // or: v = JS::StringValue(someString);
v.setNull(); // or: v = JS::NullValue();
v.setUndefined(); // or: v = JS::UndefinedValue();
v.setBoolean(false); // or: v = JS::BooleanValue(false);
获取函数参数列表
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
获取参数
int ret =args.get(0).toNumber();
获取js全局变量
JSObject *global = JS_GetGlobalForObject(cx, &args.callee());
定义一个函数
bool justForFun(JSContext *cx, unsigned argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
args.rval().setNull();
return true;
}
if (!JS_DefineFunction(cx, global, “justForFun”, &justForFun, 0, 0))
return false;
创建数组
JS::RootedObject x(cx, JS_NewArrayObject(cx, 0));
创建对象
JS::RootedObject x(cx, JS_NewPlainObject(cx));
执行js代码
JS_EvaluateScript(cx, JS::RootedObject(cx, global),script.c_str(),script.length(),”“,0);
调用全局函数
JS::RootedValue outval(cx);
jsval argv;
if (!JS_CallFunctionName(cx, *G_global, “foo”, JS::HandleValueArray::fromMarkedLocation(0, &argv), &outval))
return false;
返回值给js
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
args.rval().setInt32(23);
return true;
JS::Rooted
JSObject* localObj = JS_GetObjectOfSomeSort(cx);
You should write:
JS::Handle
JSObject * someFunction(JSContext cx, JSObject obj) {
// …
}
You should write:
JSObject * someFunction(JSContext *cx, JS::HandleObject obj) {
// …
JS::MutableHandle
bool maybeGetValue(JSContext cx, JS::Value valueOut) {
// …
if (!wasError)
*valueOut = resultValue;
return wasError;
}
void otherFunction(JSContext *cx) {
JS::Value value;
bool success = maybeGetValue(cx, &value);
// …
}
You should write:
bool maybeGetValue(JSContext *cx, JS::MutableHandleValue valueOut) {
// …
if (!wasError)
valueOut.set(resultValue);
return wasError;
}
void otherFunction(JSContext *cx) {
JS::RootedValue value(cx);
bool success = maybeGetValue(cx, &value);
// …
struct HeapStruct
{
JSObject* mSomeObject;
JS::Value mSomeValue;
};
You should write:
struct HeapStruct
{
JS::Heap