Skip to content

Instantly share code, notes, and snippets.

@draeton
Created December 9, 2011 03:48
Show Gist options
  • Save draeton/1450062 to your computer and use it in GitHub Desktop.
Save draeton/1450062 to your computer and use it in GitHub Desktop.
Nodes with children
function Node ( val, parent ) {
this.value = val;
this.setParent( parent );
this.children = [];
}
Node.prototype = {
addChild: function ( val ) {
var node = val instanceof Node ? val : new Node( val );
node.setParent( this );
this.children.push( node );
},
setParent: function ( node ) {
this.parent = node;
}
};
var a = new Node( "a" );
a.addChild("x");
a.addChild("y");
a.addChild("z");
// the node
console.log( a );
var kids = a.children;
// check parent
console.log( kids[0].parent === a ); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment