Javascript类方法响应;“不是一个函数”;

Javascript类方法响应;“不是一个函数”;,javascript,mocha.js,Javascript,Mocha.js,我正在研究一个关于树数据结构的示例,他的研究陷入了僵局 class BinaryNode { constructor(n){ // a node has data, left, and right pointers // left and right are intialized as null return {data: n, left: null, right: null} } } class BinaryTree { cons

我正在研究一个关于树数据结构的示例,他的研究陷入了僵局

class BinaryNode {
    constructor(n){
    // a node has data, left, and right pointers
    // left and right are intialized as null
      return {data: n, left: null, right: null}     
    }
}

class BinaryTree {
    constructor(){
        // when a new Tree is made, it has a root property
        return {root: null }
    }
  
    insert(data){
        // add a new Node to the tree, with data as the Node's data
        let node = BinaryNode(data)
        return BinaryNode(data)
    }
摩卡咖啡测试:

it('should place the first node as the root', ()=>{
    let tree = new BinaryTree();
    tree.insert(5);
    expect(tree.root.data).to.equal(5);
    expect(tree.root.left).to.equal(null);
    expect(tree.root.right).to.equal(null);
});
第三次测试失败,原因是:

TypeError: tree.insert is not a function
我已经花了至少两个小时来研究这个问题,但我不知道出了什么问题。 密码笔是

我想弄明白为什么这不起作用

更新
在@connexo的评论之后,我意识到我完全处于关于构造函数的白痴区域。

A
构造函数不应该
返回任何内容,必须使用
new
调用它。相反,请在此
上创建属性:

class BinaryNode {
    constructor(n) {
        // a node has data, left, and right pointers
        this.data = n;
        this.left = null;
        this.right = null;
    }
}

class BinaryTree {
    constructor(){
        this.root = null;
    }
  
    insert(data){
        // add a new Node to the tree, with data as the Node's data
        let node = new BinaryNode(data)
        … // you probably want to alter `this.root`
    }

    …
}

构造函数不应该返回任何内容。按照您的说明,构造函数只返回
{root:null}
,其他什么都不返回。如果有的话,构造函数需要返回
this
(除非您要求它执行其他操作,否则它会执行此操作)
这也是您需要附加属性的地方。另外,您的方法不是类方法(通常指静态方法),而是简单的实例方法。您返回的是没有插入的
BinaryNode
实例method@Chandan不,这根本不是问题所在。这个问题已经在评论中作了充分解释,没有其他问题。不管你觉得你发现了什么,都不存在。谢谢。我确实从@connexo的评论中了解到了这一点。