In the JSAPI, JSRuntime
is the top-level object that represents an instance of the JavaScript engine. A program typically has only one JSRuntime
, even if it has many threads. The JSRuntime
is the universe in which JavaScript objects live; they can't travel to other JSRuntime
s.
All JavaScript code and most JSAPI calls run within a JSContext
. The JSContext
is a child of the JSRuntime
. A context can run scripts. It contains the global object and the execution stack. Exception handling, error reporting, and some language options are per-JSContext
. Once created, a context can be used any number of times for different scripts or JSAPI queries. For example, a browser might create a separate context for each HTML page; every script in the page could use the same context.
Objects may be shared among JSContext
s within a JSRuntime
. There's no fixed association between an object and the context in which it is created.
Sample code to set up and tear down a JSRuntime
and a JSContext
is at JSAPI User Guide.
Threads
Only one thread may use a JSContext
at a time. In a JS_THREADSAFE
build, multiple threads may run JavaScript code concurrently in the same JSRuntime
, but each such thread must have its own JSContext
.
Ordinarily, a context is created, used, and destroyed all on the same thread. But an application can use the same JSContext
on different threads at different times (sequentially, not concurrently) by following the rules listed at JS_ClearContextThread
.