如何在节点附加组件中创建 getter?

How to create a getter in node add-on?

我一直在编写节点插件,但我似乎无法弄清楚如何将 属性 添加到 class。我一直在做的是在 c++ 附加组件中创建一个方法,并在 javascript 中创建一个调用附加组件中函数的 getter。

这是执行此操作的正确方法,还是可以在 c++ 附加组件中创建此 属性?

c++ 我这样做:

void MyAddon::Init(Local<Object> exports, Local<Object> module) {

  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyAddon"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Add the property
  NODE_SET_PROTOTYPE_METHOD(tpl, "currWidth", Width);


  // Export the class
  constructor.Reset(isolate, tpl->GetFunction());
  exports->Set(
      String::NewFromUtf8(isolate, "MyAddon"), tpl->GetFunction());
}

然后在 JavaScript 我这样做:

const MyAddon = require('./build/Release/MyAddon')

module.exports.Addon = class Addon extends MyAddon.MyAddon {
  get width() { return this.currWidth() }
}

这似乎不是向附加组件添加 属性 的正确方法。 example on the website用的是NODE_SET_METHOD,所以我试了,但不是运行的方法。我也没有收到任何错误。该方法只是不 运行...

在那个例子中,他们不会尝试将其设置在 class 上,这正是我想要做的,所以我的有点不同:

NODE_SET_METHOD((Local<Template>)tpl, "height", Height);

如何在 c++ 中创建此 属性?

Init 方法中,只需添加以下行即可:

tpl->InstanceTemplate()->SetAccessor(String::NewFromUtf8(isolate, "width"), Width);

并创建如下所示的方法:

void MyAddon::Width(Local<String> property, const PropertyCallbackInfo<Value> &args) {}