1# HandleScope
2
3The HandleScope class is used to manage the lifetime of object handles
4which are created through the use of node-addon-api. These handles
5keep an object alive in the heap in order to ensure that the objects
6are not collected while native code is using them.
7A handle may be created when any new node-addon-api Value or one
8of its subclasses is created or returned. For more details refer to
9the section titled [Object lifetime management](object_lifetime_management.md).
10
11## Methods
12
13### Constructor
14
15Creates a new handle scope on the stack.
16
17```cpp
18Napi::HandleScope::HandleScope(Napi::Env env);
19```
20
21- `[in] env`: The environment in which to construct the `Napi::HandleScope` object.
22
23Returns a new `Napi::HandleScope`
24
25### Constructor
26
27Creates a new handle scope on the stack.
28
29```cpp
30Napi::HandleScope::HandleScope(Napi::Env env, Napi::HandleScope scope);
31```
32
33- `[in] env`: `Napi::Env` in which the scope passed in was created.
34- `[in] scope`: pre-existing `Napi::HandleScope`.
35
36Returns a new `Napi::HandleScope` instance which wraps the `napi_handle_scope`
37handle passed in.  This can be used to mix usage of the C Node-API
38and node-addon-api.
39
40```cpp
41operator Napi::HandleScope::napi_handle_scope() const
42```
43
44Returns the Node-API `napi_handle_scope` wrapped by the `Napi::EscapableHandleScope` object.
45This can be used to mix usage of the C Node-API and node-addon-api by allowing
46the class to be used be converted to a `napi_handle_scope`.
47
48### Destructor
49```cpp
50Napi::HandleScope::~HandleScope();
51```
52
53Deletes the `Napi::HandleScope` instance and allows any objects/handles created
54in the scope to be collected by the garbage collector.  There is no
55guarantee as to when the garbage collector will do this.
56
57### Env
58
59```cpp
60Napi::Env Napi::HandleScope::Env() const;
61```
62
63Returns the `Napi::Env` associated with the `Napi::HandleScope`.
64
65## Example
66
67```cpp
68for (int i = 0; i < LOOP_MAX; i++) {
69  Napi::HandleScope scope(info.Env());
70  std::string name = std::string("inner-scope") + std::to_string(i);
71  Napi::Value newValue = Napi::String::New(info.Env(), name.c_str());
72  // do something with newValue
73};
74```
75
76For more details refer to the section titled [Object lifetime
77management](object_lifetime_management.md).
78