JS面向對象 對象包含對象無法調用內部對象函數的問題

[code="html"]

function TreeNode(){ this.zoom = 10; this.children = []; } var prototype = new TreeNode(); prototype.generateChildren = function() { for(var i = 0; i < 2; i++ ) { var node = new TreeNode(); this.children.push(node); } } prototype.area = function(w) { if(w <= 1) { return 1; } else { w -= 1; return this.zoom*this.area(w); } } prototype.generateChildren(); alert("children.length:" + prototype.children.length); for(var i = 0; i < prototype.children.length; i++ ) { alert(i + ":"+prototype.children[i].area(i+2)); }



[/code]

JS面向對象 對象包含對象無法調用內部對象函數的問題
报Uncaught TypeError: Cannot call method 'area' of undefined错误,
各位小虾大虾们,有空帮忙看看啊,thanks in advance!

你这里的 prototype 只是一个实例,你只是将 area 方法加到 prototype 这个 TreeNode, 将
[code="javascript"]
prototype.generateChildren = function() {

for(var i = 0; i < 2; i++ ) {

var node = new TreeNode();

this.children.push(node);

}

}

prototype.area = function(w) {

if(w <= 1) {

return 1;

} else {

w -= 1;

return this.zoom*this.area(w);

}

}

[/code]
改为
[code="javascript"]
TreeNode.prototype.generateChildren = function() {

for(var i = 0; i < 2; i++ ) {

var node = new TreeNode();

this.children.push(node);

}

}

TreeNode.prototype.area = function(w) {

if(w <= 1) {

return 1;

} else {

w -= 1;

return this.zoom*this.area(w);

}

}

[/code]