Self-references in object literals / initializers
Getters for computed properties, or factory functions for methods with self-references in object literals—these should be your go-to tools.
Getters for immediate usage:
Factory functions to encapsulate self-references:
With this
and self
, an object gains self-awareness, accessing its own properties internally.
Diving deeper: enhancing self-references
Dynamic Property Caching - The Magic of Getters
ES6 getters, those crafty little devils, create dynamic object literals while caching computed properties like a squirrel with acorns.
After initial calling, the sum
property has the stored result, preventing additional getter computations.
Self-Reference via Function Scopes
A function’s local scope is not just a privilege—it's an efficient way to create self-referential objects.
Inline Object Initialization
Invoke new function() { ... }
pattern for inline object initialization with self-references. This approach allows you to effectively use a constructor function without declaring it separately.
Advanced techniques for self-reference
Utilising Temporary Properties and Functions
Creating objects with temporary properties or functions enhances initialization. They can be removed after doing their job.
Performance Considerations: The YIN and YANG
Always remember the performance trade-offs with these complex self-referential patterns. They might be powerful, but could be the opposite of "light and fast" when overused in performance critical applications.
I mutate, therefore I exist
Once the object is created, often you might need to change some references :
This allows for external assignment post-initialization, a great way to establish self-references when complex computation isn't needed.
Was this article helpful?