电脑技术学习

JavaScript面向对象技术实现树形控件

dn001

 五、branch对象

branch对象与tree对象相似:

function branch(id, text){

this.id = id;

this.text = text;

this.write = writeBranch;

this.add = addLeaf;

this.leaves = new Array();

}

branch对象的构造函数有id和text两个参数。id是一个唯一性的标识符,text是显示在该分支的文件夹之后的文字。leaves数组是该分支对象的子元素的集合。注意branch对象定义了必不可少的write()方法,因此可以保存到tree对象的branches数组。tree对象和branch对象都定义了write()和add()方法,所以这两个方法都是多态性的。下面是branch对象的add()和write()方法的具体实现:

function addLeaf(leaf){

this.leaves[this.leaves.length] = leaf;

}

function writeBranch(){

var branchString =

'< span class="branch" ' + onClick="showBranch('' + this.id + '')"';

branchString += '>< img src="closed.gif" id="I' + this.id + '">' + this.text;

branchString += '< /span>';

branchString += '< span class="leaf" id="';

branchString += this.id + '">';

var numLeaves = this.leaves.length;

for (var j=0;j< numLeaves;j++) branchString += this.leaves[j].write();

branchString += '< /span>';

return branchString;

}

addLeaf()函数和tree对象的addBranch()函数相似,它把通过参数传入的对象加入到leaves数组的末尾。

writeBranch()方法首先构造出显示分支所需的HTML字符串,然后通过循环遍历leaves数组中的每一个对象,调用数组中每一个对象的write()方法。和branches数组一样,leaves数组也只能保存带有write()方法的对象。

 六、leaf对象

leaf对象是三个对象之中最简单的一个:

function leaf(text, link){

this.text = text;

this.link = link;

this.write = writeLeaf;

}

标签: 控件