LazyObject.js
LazyObject.js lets you define properties on an object whose values are initialized only when first accessed. From then on, values are cached/memoized.
Its defineLazyProperty
function follows the Object.defineProperty
signature
closely and allows you to change whether the defined properties are
configurable
, enumerable
and writable
.
Installing
npm install lazy-object
LazyObject.js follows semantic versioning, so feel free to
depend on its major version with something like >= 1.0.0 < 2
(a.k.a ^1.0.0
).
Using
Defining a lazily initialized property
var LazyObject = var Net = var server = {} LazyObject
Properties are by default defined as configurable
, enumerable
and
writable
. To change that, pass an options object as the last argument.
Then, like Object.defineProperty
, all unset properties are set to false
.
LazyObject
The above creates a configurable
, but non-enumerable
and non-writable
property (both before initialization and after). This prevents anyone from
overwriting the property once initalized.
Defining multiple lazy properties
var LazyObject = var Pg = var Redis = var connections = {} LazyObject
You can change the properties' enumerability by passing in an options object as the last argument:
LazyObject
The above creates the pg
and redis
properties as configurable
and writable
, but not enumerable
.
Defining lazy properties on the prototype
You don't have to define properties directly on the object you want them on. Taking advantage of prototypical inheritance, you can do so only once on the prototype:
var LazyObject = var Net = { if host != null thishost = host if port != null thisport = port} Telnetprototypehost = nullTelnetprototypeport = 23 LazyObject
Then, only when you first access the connection
property on a new Telnet
instance, will the connection be created. Different Telnet
instances get their
own connections.
License
LazyObject.js is released under a Lesser GNU Affero General Public License, which in summary means:
- You can use this program for no cost.
- You can use this program for both personal and commercial reasons.
- You do not have to share your own program's code which uses this program.
- You have to share modifications (e.g. bug-fixes) you've made to this program.
For more convoluted language, see the LICENSE
file.
About
Andri Möll typed this and the code.
Monday Calendar supported the engineering work.
If you find LazyObject.js needs improving, please don't hesitate to type to me now at andri@dot.ee or create an issue online.