Context Creation
These functions manage the lifecycle of JavaScript contexts (JSContext). A context represents a JavaScript realm with its own global objects and system objects. Multiple contexts can exist within a single runtime and share objects, similar to how frames of the same origin share JavaScript objects in a web browser.
JS_NewContext
Creates a new JavaScript context with all standard intrinsic objects.The runtime in which to create the context
JSContext pointer, or NULL on failure.
Description
This function creates a fully-featured JavaScript context with all standard intrinsic objects including:- Base objects (Object, Function, Array, etc.)
- Date
- Eval
- RegExp
- JSON
- Proxy
- Map and Set
- TypedArrays
- Promise
- BigInt
JS_NewContextRaw() combined with selective intrinsic functions to create a minimal context.
Example
JS_FreeContext
Frees a JavaScript context and releases all associated resources.The context to free
Description
This function releases all resources associated with the context, including:- All JavaScript objects created in the context
- The global object and its properties
- All pending exceptions
- Internal data structures
Important Notes
- Always call
JS_FreeContext()beforeJS_FreeRuntime() - All
JSValueobjects created in this context should be freed before calling this function - Do not use the context pointer after calling this function
Example
JS_DupContext
Creates a new context that shares the same runtime and global objects.The context to duplicate
JSContext pointer that shares objects with the original context, or NULL on failure.
Description
This function creates a new context within the same runtime. The new context:- Shares the same global object as the original context
- Can access and modify objects from the original context
- Behaves like the same JavaScript realm
- Must be freed separately with
JS_FreeContext()
Example
Related Functions
JS_NewContextRaw()- Create a minimal context without intrinsic objectsJS_GetRuntime()- Get the runtime associated with a contextJS_GetContextOpaque()/JS_SetContextOpaque()- Attach custom data to a contextJS_GetGlobalObject()- Get the global object for a context