Search code examples
c++v8embedded-v8

How to create global object with static methods in v8 engine?


I want to have the same object as JSON in my embedded v8. So I can have several static methods and use it like this:

MyGlobalObject.methodOne();
MyGlobalObject.methodTwo();

I know how to use Function template for the global function but I can not find any example for global object with static methods.


Solution

  • In short: use ObjectTemplates, just like for the global object you're setting up.

    There are several examples of this in V8's d8 shell. The relevant excerpts are:

    Local<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
    Local<ObjectTemplate> d8_template = ObjectTemplate::New(isolate);
    Local<ObjectTemplate> file_template = ObjectTemplate::New(isolate);
    file_template->Set(isolate, "read",
                       FunctionTemplate::New(isolate, Shell::ReadFile));
    d8_template->Set(isolate, "file", file_template);
    global_template->Set(isolate, "d8", d8_template);
    Local<Context> context = Context::New(isolate, nullptr, global_template);
    

    That snippet results in a function d8.file.read(...) being available.