I have been in the process of writing a node add-on, and I cannot seem to figure out how add a property to a class. What I have been doing is creating a method in the c++
add-on, and in the javascript
I create a getter that calls the function in the add-on.
Is this the correct way to do this, or can this property be created in the c++
add-on?
In the c++
I do this:
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());
}
Then in the JavaScript
I do this:
const MyAddon = require('./build/Release/MyAddon')
module.exports.Addon = class Addon extends MyAddon.MyAddon {
get width() { return this.currWidth() }
}
This doesn't seem like the correct way to add a property to the add-on. The example on the website uses NODE_SET_METHOD
, so I tried but it doesn't run the method. I don't get any errors either. The method just doesn't run...
In there example they don't try to set it on a class, which is what I am trying to do, so mine is a little different:
NODE_SET_METHOD((Local<Template>)tpl, "height", Height);
How can I create this property in the c++
?
In the
Init
method, it was as easy as adding this line:And creating a method that looks like this: