Visit Mozilla.org

jsval

From MDC

jsval is the type of JavaScript values in the JSAPI.

A C/C++ variable of type jsval can hold exactly the same values as a JavaScript var or property: string, number, object, boolean, null, or undefined. (Arrays, functions, and Errors are all objects.)

jsval is a variant type, currently implemented as a tagged pointer/scalar that fits in a single pointer-sized word. The type tag, which is currently stored in the least significant 1-to-3 bits of the word, indicates whether the jsval is an integer, a pointer to a JSString, a pointer to a JSObject, etc.

The are two major caveats about working with jsvals.

[edit] jsval is not particularly type-safe

In the current implementation of SpiderMonkey, jsval is an integer type, but applications must treat it as an opaque type. The data in a jsval can be accessed using these JSAPI macros and functions:

JS type jsval type tests jsval constants and constructors jsval accessors
null JSVAL_IS_NULL(v) JSVAL_NULL
undefined JSVAL_IS_VOID(v) JSVAL_VOID
boolean JSVAL_IS_BOOLEAN(v) JSVAL_TRUE, JSVAL_FALSE, BOOLEAN_TO_JSVAL(b) JSVAL_TO_BOOLEAN(v)
number JSVAL_IS_NUMBER(v), JSVAL_IS_INT(v), JSVAL_IS_DOUBLE(v) JSVAL_ZERO, JSVAL_ONE, INT_TO_JSVAL(i), DOUBLE_TO_JSVAL(p) JSVAL_TO_INT(v), JSVAL_TO_DOUBLE(v) (Note that JSVAL_TO_DOUBLE returns a pointer to a jsdouble, not the floating-point value itself.)
string JSVAL_IS_STRING(v) STRING_TO_JSVAL(str) JSVAL_TO_STRING(v), JS_GetStringChars(str), JS_GetStringLength(str)
object JSVAL_IS_OBJECT(v) OBJECT_TO_JSVAL(obj) JSVAL_TO_OBJECT(v)
Warning sign
Warning: The JSVAL_TO_x macros 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.

[edit] jsvals are subject to garbage collection

A jsval can refer to a string, object, or number 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.