javascript - 类型错误 : 'addNode' is not a function

标签 javascript p5.js

我编写了一个简单的 JavaScript p5 应用程序(使用 p5.js)来创建 BST 数据结构。使用 Firefox 运行时,它向我显示 TypeError: this.root.addNode is not a function
有人可以帮忙吗?这是完整代码(错误在第20行)

var tree;

function setup() {
  noCanvas();
  tree = new Tree();
  tree.addValue(5);
  tree.addValue(3);
  console.log(tree);
}

function Tree() {
  this.root = null;
}

Tree.prototype.addValue = function (val) {
  var n = new Node(val);
  if (this.root == null) {
    this.root = n;
  } else {
      this.root.addNode(n);
  }
}

Tree.prototype.addNode = function (n) {
  if (n.value < this.value)
    if (this.left == null) {
      this.left = n;
    } else {
      this.left.addNode(n);
    }
  } else if (n.value > this.value) {
    if (this.right == null) {
      this.right = n;
    } else {
      this.right.addNode(n);
    }
  }
}

function Node(val) {
  this.value = val;
  this.left = null;
  this.right = null;
}

最佳答案

root 只是您稍后指定为 Node 的属性。您将原型(prototype)函数 addNode 分配给 TreeNode 没有。要么设置

this.root = new Tree();

或者将原型(prototype)方法 addNode 分配给 Node

关于javascript - 类型错误 : 'addNode' is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50787165/

相关文章:

javascript - 客户端的分面搜索

javascript - 到达最后一行时增加文本区域的高度

javascript - 使用 javascript trim 音频文件(前 3 秒)

javascript - 函数 arc() 无法在 p5.js 中正确呈现

javascript - p5.j​​s 手动调用setup和draw

javascript - JS 和 Html 中未捕获的语法错误意外标识符

javascript - 使用 PHP(wordpress)从数据库中删除图像及其在数据库中的记录

javascript - ajax调用后无法调用jquery

javascript - this.type ='password' 在 IE 中不起作用,但它在所有其他浏览器中都起作用

javascript - OpenWeather API 错误