Browse DevX
Sign up for e-mail newsletters from DevX


Build an Object-Oriented Tree Control Using JavaScript : Page 3

When you need to display hierarchical information in your Web pages, build this Explorer-like tree control by creating only three polymorphic JavaScript objects.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Set up the Tree Object
Add the tree object's constructor to the script:

function tree(){ this.branches = new Array(); this.add = addBranch; this.write = writeTree; }

The tree object represents the root node of the tree. The tree() constructor guarantees that each tree object has an array called branches that serves as the collection of children of the tree. . The add and write properties are the polymorphic methods, implemented as pointers to the following functions:

function addBranch(branch){ this.branches[this.branches.length] = branch; } function writeTree(){ var treeString = ''; var numBranches = this.branches.length; for (var i=0;i <numBranches;i++) treeString += this.branches[i].write(); document.write(treeString); }

The addBranch() method appends the object passed to the method onto the end of the branches array. The writeTree() method loops through all of the objects stored in the branches array and calls the write() method of each object. That's the beauty of polymorphism; you can call the polymorphic write() method because each object in the branches array implements its own appropriate version of the write() method. Note that, although JavaScript's Array object lets you store anything you'd like in an array, in this implementation you can store only objects that implement a write() method in the branches array. Unlike other more strongly typed languages, JavaScript won't enforce that rule; you need to enforce it yourself.

Thanks for your registration, follow us on our social networks to keep up-to-date