create wiki

go home go home
  1. about
  2. code
  3. wiki
  4. blog

V8/Contexts

From Create Wiki

Jump to: navigation, search

All code in V8 executes in a context.

Why? Think of a web browser. You can have multiple tabs open, and each tab may have some of its own scripts. The scripts from one tab should be completely independent of the scripts of any other tab. In a browser using v8, each tab would have its own context, and thus its own set of scripts, its own global object, etc.

What Needs a Context?

Obviously, executing any code requires a context. In addition, v8 object instances require a context. If you try to call ObjectTemplate::NewInstance outside of a context, your application will crash.

Creating and Entering a Context

Creating a context is very simple, but just creating a context is not enough. You also need to tell v8 that any code execution or object instances will belong to that context. This distinction allows the program to switch between contexts.

The simplest way to create a context is through a context scope, which is really just a convenient way of calling a context's Enter and Exit functions automatically.

//create context
Pesistent<Context> context = Context::New();
 
{ //braces to create a new scope for demonstration
    //create scope, calling Context::Enter
    Context::Scope context_scope(context);
 
    //now you can do things
}
 
//Context::Exit was called when the scope ended.
Personal tools