Skip to content
Craig Minihan edited this page Apr 20, 2015 · 20 revisions

A context is a scope within a SpiderMonkey runtime. When you create a rs::jsapi::Runtime you automatically get a default context in which to run your JavaScript code. If you don't need to run multiple instances of SpiderMonkey inside your application then you may never need to create a context directly.

In this example we create two contexts and define global variables in each:

#include "libjsapi.h"
int main() {
  rs::jsapi::Runtime rt;
  
  // create a global variable in the default context
  rt.Evaluate("var myVar = 'hello world';");

  // create another global variable in another context
  auto context = rt.NewContext();
  context->Evaluate("var myVar = 'lorem ipsum';");

  return 0;
}

The two myVar variables are completely separate, defined only within the scope of their own contexts. It is not possible to refer to a variable from a different context within the JavaScript code.

If your application has more than one thread then you are free to create contexts within the new threads.

Clone this wiki locally