JavaScript extract class: Solve circular pointer reference

When doing extract class refactorings the new sub- or helper-class requires a backreference to its creator and the creator needs a reference to its helper to make it accessible.

The issue with that structure is, that all those references have to be destructed manually which easily leads to memory leaks when one circular reference is forgotten to destruct.

Simplified Example:

function MasterClass(name) { = name;
    this.extension = new MasterClassExtension(this);

function MasterClassExtension(masterClass) {
    this.masterClass = masterClass;

MasterClassExtension.prototype.beautifiedName = function () {
   return 'Beautiful ' +;


new MasterClass('Tux').extension.beautifiedName(); // Returns "Beautiful Tux".

I know "Don't do work in constructor." but chose it for the sake of simplicity. Anyway, in an environment like PHP this does not matter as the process shuts down after the request is processed, but it does for continously running server structures like in Node.js or single page web apps.

Solution 1 Passing the reference any time.

var masterClass = new MasterClass('Tux');
MasterClassExtension.beautifiedName(masterClass); // Using singleton.


  • No circular reference problem.


  • Requires singletons (may cause unit testing issues).
  • The extension methods have to pass the reference and parameters forth to each other when there are more complex tasks, resulting in ugly function signatures.

Solution 2 Destructing.

var masterClass = new MasterClass('Tux');
masterClass.destruct(); // Sets this.extension = null;
masterClass = null;


  • As handy to use as intended, except for the destructor part.


  • The destruction is not enforced and can easily be forgotten causing memory leaks.

Solution 3 [???]

Is there a better solution / pattern / approach for solving this problem?



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.