首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >TypeError:“addNode”不是函数

TypeError:“addNode”不是函数
EN

Stack Overflow用户
提问于 2018-06-11 03:08:57
回答 2查看 212关注 0票数 1

我编写了一个简单的JavaScript p5应用程序(使用p5.js)来创建BST数据结构。当我在火狐上运行它时,它显示了TypeError: this.root.addNode is not a function

有人能帮帮忙吗?这是完整的代码(错误在第20行)

代码语言:javascript
复制
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;
}
EN

回答 2

Stack Overflow用户

发布于 2018-06-11 03:16:45

root只是一个稍后指定为Node的属性。你将原型函数addNode赋值给TreeNode没有这个。任一组

代码语言:javascript
复制
this.root = new Tree();

或者改为将原型方法addNode分配给Node

票数 1
EN

Stack Overflow用户

发布于 2018-06-11 03:34:21

如果你感兴趣,这就是你可以使用class关键字实现它的方式,它为你处理了很多手动的原型处理,所以它不太容易出错。

代码语言:javascript
复制
class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
  }
}

class Tree {
  constructor() {
    this.root = null;
  }

  _insert(target, key) {
    if (target.key > key) {
      if (!target.left) {
        target.left = new Node(key);
      } else {
        this._insert(target.left, key);
      }
    } else {
      if (!target.right) {
        target.right = new Node(key);
      } else {
        this._insert(target.right, key);
      }
    }
  }

  insert(key) {
    if (!this.root) {
      this.root = new Node(key);
    } else {
      this._insert(this.root, key);
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50787165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档