Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 8dc05e4

Browse filesBrowse files
mhdawsonMylesBorins
authored andcommitted
doc: document common pattern for instanceof checks
PR-URL: #16699 Fixes: #13824 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 7fe6a8f commit 8dc05e4
Copy full SHA for 8dc05e4

File tree

Expand file treeCollapse file tree

1 file changed

+23
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+23
-0
lines changed
Open diff view settings
Collapse file

‎doc/api/n-api.md‎

Copy file name to clipboardExpand all lines: doc/api/n-api.md
+23Lines changed: 23 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.