Skip to content

Instantly share code, notes, and snippets.

@Klortho
Created May 25, 2016 20:00
Show Gist options
  • Save Klortho/b2d3cfed3b8334db83e5d3aaf452ddcd to your computer and use it in GitHub Desktop.
Save Klortho/b2d3cfed3b8334db83e5d3aaf452ddcd to your computer and use it in GitHub Desktop.
Circular object reference in JavaScript without mutation
const Node = function(node) {
this.other = (typeof node === 'undefined') ? new Node(this) : node;
};
console.log(new Node()); //=> { other: { other: [Circular] } }
@Klortho
Copy link
Author

Klortho commented May 25, 2016

But I hate that assignment statement -- still a whole lotta mutating going on. This, for example, does not work:

const newNode = function(node) {
  const self = {
    other: typeof node === 'undefined' ? newNode(self) : node
  };
  return self;
};

// ReferenceError: self is not defined:
console.log(newNode()); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment