Skip to content

Instantly share code, notes, and snippets.

@a7ul
Created June 15, 2018 10:56
Show Gist options
  • Save a7ul/ab4b416038c469d3453929403691f93d to your computer and use it in GitHub Desktop.
Save a7ul/ab4b416038c469d3453929403691f93d to your computer and use it in GitHub Desktop.
blog-on-node-addon-complex-obj
diff --git a/cppsrc/Samples/classexample.cpp b/cppsrc/Samples/classexample.cpp
index 8dfa3cc..834f7ea 100644
--- a/cppsrc/Samples/classexample.cpp
+++ b/cppsrc/Samples/classexample.cpp
@@ -22,8 +22,17 @@ ClassExample::ClassExample(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Cl
Napi::HandleScope scope(env);
int length = info.Length();
- if (length != 1 || !info[0].IsNumber()) {
- Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
+
+ if (length != 1) {
+ Napi::TypeError::New(env, "Only one argument expected").ThrowAsJavaScriptException();
+ }
+
+ if(!info[0].IsNumber()){
+ Napi::Object object_parent = info[0].As<Napi::Object>();
+ ClassExample* example_parent = Napi::ObjectWrap<ClassExample>::Unwrap(object_parent);
+ ActualClass* parent_actual_class_instance = example_parent->GetInternalInstance();
+ this->actualClass_ = new ActualClass(parent_actual_class_instance->getValue());
+ return;
}
Napi::Number value = info[0].As<Napi::Number>();
@@ -51,4 +60,8 @@ Napi::Value ClassExample::Add(const Napi::CallbackInfo& info) {
double answer = this->actualClass_->add(toAdd.DoubleValue());
return Napi::Number::New(info.Env(), answer);
+}
+
+ActualClass* ClassExample::GetInternalInstance() {
+ return this->actualClass_;
}
diff --git a/cppsrc/Samples/classexample.h b/cppsrc/Samples/classexample.h
index 1f0cf69..7f6237f 100644
--- a/cppsrc/Samples/classexample.h
+++ b/cppsrc/Samples/classexample.h
@@ -5,6 +5,7 @@ class ClassExample : public Napi::ObjectWrap<ClassExample> {
public:
static Napi::Object Init(Napi::Env env, Napi::Object exports);
ClassExample(const Napi::CallbackInfo& info);
+ ActualClass* GetInternalInstance();
private:
static Napi::FunctionReference constructor;
diff --git a/index.js b/index.js
index d849e0e..efce991 100644
--- a/index.js
+++ b/index.js
@@ -3,8 +3,13 @@ console.log('addon',testAddon);
console.log('hello ', testAddon.hello());
console.log('add ', testAddon.add(5, 10));
+const prevInstance = new testAddon.ClassExample(4.3);
+console.log('Initial value : ', prevInstance.getValue());
+console.log('After adding 3.3 : ', prevInstance.add(3.3));
+
+const newFromExisting = new testAddon.ClassExample(prevInstance);
+
+console.log('Testing class initial value for derived instance');
+console.log(newFromExisting.getValue());
-const classInstance = new testAddon.ClassExample(4.3);
-console.log('Testing class initial value : ',classInstance.getValue());
-console.log('After adding 3.3 : ',classInstance.add(3.3));
module.exports = testAddon;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment