Search code examples
v8

V8: How to use Set method on a Persistent handler?


I need to set properties on an object referenced by a Persistent handler. However, it seems like Persistent class doesn't have a Set method (unlike the Local class).

Does it mean that Persistent handlers are read only? What is the best way to set a property on a Persistent handler then?


Solution

  • Create a v8::Local from the v8::Persistent, then use that to call operations on the object (Set and/or others). Note that you need an active HandleScope for this.

    v8::Persistent<v8::Object> my_persistent = ...;
    
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> obj = v8::Local<v8::Object>::New(isolate, my_persistent);
    obj->Set(...);
    

    (To be nitpicky: Local doesn't have a Set method either; what it does have is an operator-> overload that lets you call methods (including Set) on the thing that the Local refers to. If that thing isn't a v8::Object but e.g. a v8::Number, then it won't have a Set method.)