xun_2008 2012-05-08 16:57
浏览 241
已采纳

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!

  • 写回答

1条回答 默认 最新

  • iteye_4905 2012-05-08 17:23
    关注

    你这里的 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]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作