Search code examples
c++node.jsv8

How does v8 scoping work?


This question can be narrowed down to:

  • What's the difference between Handle, Persistent and Local?
  • How to properly dispose of each?
  • When dealing with Locals, how exactly to work with HandleScope in cases where, for instance, I don't have any return values? (I've only seen examples where scope.Close(value) is returned).

Solution

  • Think of HandleScopes as a stack -- each time you create one, it's the newest scope. As they go out of scope, any Local<> created after that HandleScope can be deleted/GC'd.

    Persistent<> is untouched by HandleScope and should only be removed with Dispose.

    If you are returning a value from a function, you create that as a Local and then, call scope.Close(myLocalObject) which passes ownership of that object from the created scope to the parent scope. Functions not returning anything still must return an undefined e.g. scope.Close(Undefined());

    edit

    Handle is just the base class for Local and Persistent. There's good information on scoping and handles on the v8 developer site: https://developers.google.com/v8/embed

    Re: returning args.this, that's used in a constructor function (e.g. new MyObject) if you look in the comments in the example code on that page.