Introduction
Welcome to the documentation for odweakify, a lightweight library for weakening object references in JavaScript.
Installation
To install odweakify, you can use npm or yarn:
npm install odweakify
yarn add odweakify
Usage
import { weakify } from 'odweakify';
// Creating weak references
const obj = { value: 'Hello' };
const weakRef = weakify(obj);
// Accessing the weakly referenced object
console.log(weakRef.deref()); // Output: { value: 'Hello' }
Advanced Usage
// Check if weak references are supported
const isSupported = weakify.isSupported();
if (isSupported) {
console.log('Weak references are supported');
} else {
console.log('Weak references are not supported');
}
// Using WeakMap directly
const weakMap = new WeakMap();
const key = { id: 'someId' };
weakMap.set(key, 'Some value');
console.log(weakMap.get(key)); // Output: 'Some value'
// Using weakify.create()
const weakRef2 = weakify.create();
weakRef2.set(key, 'Another value');
console.log(weakRef2.get(key)); // Output: 'Another value'
API Reference
Class: weakify
Method: weakify.isSupported()
Checks whether weak references are supported in the current environment.
- Returns:
true
if weak references are supported,false
otherwise.
Class: WeakRef
Method: WeakRef#deref()
Returns the weakly referenced object, or undefined
if the object has been garbage collected.
- Returns: The weakly referenced object or
undefined
.
Class: WeakMap
Method: WeakMap#set(key, value)
Sets the value for the specified key in the WeakMap object.
- key (Object): The key of the element to add to the WeakMap.
- value (Any): The value of the element to add to the WeakMap.
Method: WeakMap#get(key)
Returns the value for the specified key in the WeakMap object.
- key (Object): The key of the element to return from the WeakMap.
- Returns: The value associated with the specified key, or
undefined
if the key is not found.
Conclusion
Congratulations! You have successfully learned how to use odweakify to create and work with weak references in your JavaScript applications.
For more information, check out the odweakify GitHub repository.