在 Nan::ObjectWrap C++ Class 中存储 JavaScript 实例的正确方法

Proper Method for Storing JavaScript Instances in Nan::ObjectWrap C++ Class

假设我有两个用 C++ 开发的 classes,但使用 Nan NodeJS 本机模块公开。例如,"Sprite" 和 "Texture" class.

在 JavaScript 中,我希望能够让 Sprite 存储纹理,就好像它只是另一个 属性:

// Local instance of texture
var t = new Texture();

// Global instances of Sprites that won't be GC'd
global.spr = new Sprite();
global.spr2 = new Sprite();

// Same texture can be assigned to multiple sprites
spr.texture = t;
spr2.texture = t;

console.log(spr.texture);

在 C++ 方面,Sprite 的 "texture" 属性 将是存储或检索纹理的 Getter/Setter。但问题是,在内部存储 Texture 实例的正确方法是什么(来自提供的 v8::Local)?比如,我需要做什么才能通过 Sprite 将其注册为 "owned" 并导致它不会像上面的示例中那样获得 GC?

您可以将 Persistent 句柄作为存储 Texture 实例的 Sprite class 的成员。 Sprite 析构函数需要重置句柄以避免泄漏。

class Sprite : public Nan::ObjectWrap {
public:
  Nan::Persistent<v8::Object> textureHandle;

  static NAN_SETTER(SetTexture) {
    Sprite* sprite = Nan::ObjectWrap::Unwrap<Sprite>(info.This());
    if (Nan::New(Texture::constructor)->HasInstance(value)) {
      sprite->textureHandle.Reset(value);
    } else {
      // value wasn't a Texture instance; do something
    }
  }

  static NAN_GETTER(GetTexture) {
    Sprite* sprite = Nan::ObjectWrap::Unwrap<Sprite>(info.This());
    Isolate* iso = Isolate::GetCurrent();
    if (sprite->textureHandle.IsEmpty()) {
      // Texture hasn't been set yet; do something
    } else {
      info.GetReturnValue().Set(sprite->TextureHandle.Get(iso));
    }
  }

  ~Sprite() {
    textureHandle.Reset();
  }
}

(未显示:注册getter/setter的初始化代码。)