Skip to content

Commit 58e47e8

Browse files
committed
doc: document common pattern for instanceof checks
Fixes: nodejs#13824
1 parent c42cdd4 commit 58e47e8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

doc/api/n-api.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3021,6 +3021,29 @@ constructor and methods can be called from JavaScript.
30213021
callback, [`napi_unwrap`][] obtains the C++ instance that is the target of
30223022
the call.
30233023

3024+
For wrapped objects it may be difficult to distinguish between a function
3025+
called on a class prototype and a function called on an instance of a class.
3026+
A common pattern used to address this problem is to save a persistent
3027+
reference to the class constructor for later `instanceof` checks.
3028+
3029+
As an example:
3030+
3031+
```
3032+
napi_value MyClass_constructor = nullptr;
3033+
status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);
3034+
assert(napi_ok == status);
3035+
bool is_instance = false;
3036+
status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);
3037+
assert(napi_ok == status);
3038+
if (is_instance) {
3039+
// napi_unwrap() ...
3040+
} else {
3041+
// otherwise...
3042+
}
3043+
```
3044+
3045+
Of course you also need to make sure to free the reference once it is no longer needed.
3046+
30243047
### *napi_define_class*
30253048
<!-- YAML
30263049
added: v8.0.0

0 commit comments

Comments
 (0)