-
Notifications
You must be signed in to change notification settings - Fork 3
JSAPI Types
The SpiderMonkey type system is fairly easy to use. However since JavaScript is a dynamic language it has a garbage collector to manage object lifetime, this adds an extra layer of complexity.
From a C++ perspective the fundamental JavaScript types are:
- JSObject (which includes arrays)
- int32
- double
- boolean
- null
- undefined
- JSFunction
JavaScript type instances are subject to garbage collection. In libjsapi type instances are rooted in the context for the duration of the C++ call. This is achieved by the template type JS::Rooted<T>. In JSAPI this would be implemented as follows:
JS::RootedString str(cx, JS_NewStringCopyZ(cx, "hello world"));This declaration creates a new JSString* and roots that instance in the context cx. When str goes out of scope then the root is removed which makes the JSString* available for garbage collection.
Fortunately libjsapi makes dealing with JavaScript types slightly easier:
rs::jsapi::Value str(cx, "hello world");The rs::jsapi::Value class automatically roots the new string in the scope of the context, and as with RootedString it removes the root once it goes out of scope.
The rs::jsapi::Value class is a simple wrapper around JS::RootedValue and JS::RootedObject; exposing operators for JS::Handle* and JS::Mutable* means it plays as well with JSAPI function calls as with libjsapi itself. For example:
rs::jsapi::Value num(cx, 42);
JS::MutableValueHandle mvh(num);
mvh.setNumber(99);In this example JS::MutableHandleValue changes the value of the num variable from 42 to 99. When calling JSAPI functions rs::jsapi::Value is implicitly cast to a handle or mutable handle where appropriate.
The following rs::jsapi::Value methods can be used to determine the type of the JavaScript object contained:
- isNumber
- isInt32
- isBoolean
- isString
- isObject
- isArray
- isNull
- isUndefined
To get the value from an instance of Value use the to* methods:
- toNumber
- toInt32
- toBoolean
- toString (returns a JString*)
- toObject (returns a JObject*)
In addition Value exposes the method ToString which converts the instance to a string by applying the same rules the JavaScript function toString() uses. So for example: [1,2,3].toString() yields "1,2,3".