A C/C++ variable of type
var or property: string, number, object, boolean,
undefined. (Arrays, functions, and
Errors are all objects.)
jsval is a variant type whose exact representation varies by architecture. Embeddings should not rely on observed representation details, the size of jsval, or whether jsval is a primitive type.
The are two major caveats about working with
jsval is not particularly type-safe
The data in a
jsval can be accessed using these JSAPI macros and functions:
|JS type|| || || |
| || || |
| || || |
|boolean|| || || |
|number|| || || |
|string|| || || |
|object|| || || |
JSVAL_TO_x functions use C casts and bit twiddling. They are only safe if you already know that the
jsval is of exactly the right type. Calling
JSVAL_TO_DOUBLE() on an int
jsval, for instance, triggers undefined behavior and will probably lead to a crash.") }}
jsvals are subject to garbage collection
jsval can refer to a string or object that's located in SpiderMonkey's garbage-collected heap.
The garbage collector is designed to automatically free unreachable memory. It is rather eager about its job. It's like a robot that goes around picking up everything that isn't nailed down and putting it in the trash. If an application has a
jsval variable that refers to a
JSObject, the garbage collector might not know you're using the
JSObject. So it might free it, leaving a dangling pointer. The solution is to tell SpiderMonkey that you're using the object, then tell it again when you're done.
In short, your
jsvals must be rooted or your program will randomly crash. In some places, SpiderMonkey provides already-rooted
jsvals which you can use for variables. See SpiderMonkey Garbage Collection Tips.