Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
doc: document common pattern for instanceof checks
Fixes: #13824
  • Loading branch information
mhdawson committed Nov 2, 2017
commit 58e47e8a3c8c1c1020bb210e3b0d78a9c35cf4ea
23 changes: 23 additions & 0 deletions doc/api/n-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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() ...
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should indentation be two spaces here and a couple lines down?

} else {
// otherwise...
}
```

Of course you also need to make sure to free the reference once it is no longer needed.

### *napi_define_class*
<!-- YAML
added: v8.0.0
Expand Down