Skip to content

Commit 8dc05e4

Browse files
mhdawsonMylesBorins
authored andcommitted
doc: document common pattern for instanceof checks
PR-URL: #16699 Fixes: #13824 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent 7fe6a8f commit 8dc05e4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

doc/api/n-api.md

+23
Original file line numberDiff line numberDiff line change
@@ -3022,6 +3022,29 @@ constructor and methods can be called from JavaScript.
30223022
callback, [`napi_unwrap`][] obtains the C++ instance that is the target of
30233023
the call.
30243024

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

0 commit comments

Comments
 (0)