递归中的Javascript'this'上下文?

时间:2015-08-05 18:04:57

标签: javascript algorithm

在JS中编写一个简单的BST实现,我遇到了一些我不理解的东西。代码如下:

var Node = function(time, value) {
  // has time and value
  this.time = time;
  this.value = value;

  this.left;
  this.right;

  // we have an insert method.
  var insert = function(time, value) {
    if (time <= this.time) {
      // go left
      if (!this.left) {
        this.left = new Node(time, value);
      } else {
        this.left.insert(time, value);
      }
    } else {
      // go right
      if (!this.right) {
        this.right = new Node(time, value);
      } else {
        this.right.insert(time, value);
      }
    }
  }

  this.insert = insert;

  // we have a find method
  var that = this;
  var find = function(time) {
    if (time === that.time) {
      // we found the node, let's return this one
      console.log("%%%" + **that.value**);
      return **that.value**;
    }

    if (time > that.time) {
      this.right.find(time); 
    } else {
      this.left.find(time); 
    }
  }

  this.find = find;
}

var a1 = new Node(3, "aad");
a1.insert(9, "bbasd");
a1.insert(5, "caadfas");
a1.insert(10, "daddaf");

console.log(a1.find(3));
console.log(a1.find(5));
console.log(a1.find(9));
console.log(a1.find(10));

输出:

%%aad 
aad 
%%caadfas 
undefined 
%%bbasd 
undefined 
%%daddaf 
undefined 

为什么控制台打印行具有正确的this.value但返回的this.value未定义?

谢谢!

1 个答案:

答案 0 :(得分:3)

您没有通过“左”或“右”链接返回调用.find()的结果。你只是调用函数并抛弃结果。

相反:

if (time > that.time) {
  return this.right.find(time); 
} else {
  return this.left.find(time); 
}