From 58e47e8a3c8c1c1020bb210e3b0d78a9c35cf4ea Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Thu, 2 Nov 2017 18:14:24 -0400 Subject: [PATCH 1/3] doc: document common pattern for instanceof checks Fixes: https://github.com/nodejs/node/issues/13824 --- doc/api/n-api.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 7bd20c60b60ea1..7ce19efbb3f021 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -3021,6 +3021,29 @@ constructor and methods can be called from JavaScript. callback, [`napi_unwrap`][] obtains the C++ instance that is the target of the call. +For wrapped objects it may be difficult to distinguish between a function +called on a class prototype and a function called on an instance of a class. +A common pattern used to address this problem is to save a persistent +reference to the class constructor for later `instanceof` checks. + +As an example: + +``` +napi_value MyClass_constructor = nullptr; +status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor); +assert(napi_ok == status); +bool is_instance = false; +status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance); +assert(napi_ok == status); +if (is_instance) { + // napi_unwrap() ... +} else { + // otherwise... +} +``` + +Of course you also need to make sure to free the reference once it is no longer needed. + ### *napi_define_class*