今天在看完xtree.js代码后,发现一个问题。在执行javascript的document.write(obj)方法时,如果obj实现了prototype的toString()方法,document.wirte方法将能自动调用obj的toString()方法。代码如下:
/*---------- 树构造代码 ---------*/
if (document.getElementById) {
var tree = new WebFXTree('Root');
tree.setBehavior('classic');
var a = new WebFXTreeItem('1');
tree.add(a);
var b = new WebFXTreeItem('1.1');
a.add(b);
b.add(new WebFXTreeItem('1.1.1'));
b.add(new WebFXTreeItem('1.1.2'));
b.add(new WebFXTreeItem('1.1.3'));
var f = new WebFXTreeItem('1.1.4');
b.add(f);
document.write(tree);
/*------------------ xtree.js代码片段 ----------*/
WebFXTree.prototype.toString = function() {
alert("it's here!");
var str = "<div id=\"" + this.id + "\" ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this, event)\">" +
"<img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\">" +
"<a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\"" +
(this.target ? " target=\"" + this.target + "\"" : "") +
">" + this.text + "</a></div>" +
"<div id=\"" + this.id + "-cont\" class=\"webfx-tree-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">";
var sb = [];
for (var i = 0; i < this.childNodes.length; i++) {
sb[i] = this.childNodes[i].toString(i, this.childNodes.length);
}
this.rendered = true;
return str + sb.join("") + "</div>";
};
经过跟踪,证实在执行document.write(tree)时,调用了
WebFXTree.prototype.toString 方法。
posted on 2009-08-13 16:20
zhangxl 阅读(1004)
评论(1) 编辑 收藏