JavaScript中序遍历函数报错‘Inorder未定义’求助
解决"Inorder is not defined"错误的方法
嘿,我一眼就看出问题所在啦!你在Tree类的Inorder方法里直接递归调用Inorder(root.left),但这个方法是Tree类的成员方法,不是全局函数,JavaScript自然找不到它~
错误原因
在类的方法内部,直接写Inorder()会去全局作用域查找这个函数,但你的Inorder是绑定在Tree实例上的方法,必须通过this关键字来引用当前实例的方法才行。
修正后的代码
只需要把递归调用的地方改成this.Inorder()就可以了:
class Tree { constructor(root) { this.root = root; } Inorder(root) { if (root == null) { return; } this.Inorder(root.left); // 加上this引用当前实例的方法 console.log(root.data); this.Inorder(root.right); // 同样加上this } } class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } const obj = new Node(5); obj.left = new Node(10); obj.right = new Node(15); obj.left.left = new Node(16); obj.right.right = new Node(17); const tree = new Tree(obj); console.log(tree.root.data); tree.Inorder(tree.root);
额外小提示
如果担心this上下文在某些复杂场景下丢失(比如嵌套箭头函数、回调函数里),也可以提前把this存起来,比如在方法开头加一行:
const self = this;
然后递归的时候用self.Inorder(root.left)来调用,不过在你当前的场景里,直接用this就完全没问题啦~
内容的提问来源于stack exchange,提问作者batman007
相关产品推荐
相关产品推荐

