Javascript递归函数引用此

时间:2013-12-12 03:44:56

标签: javascript recursion tree

我正在尝试创建一个生成树状结构的函数,以便每个项目都包含对其父项的引用。

我有一个在创建子项时调用自身但在使用它时遇到困难的函数,似乎一旦从内部调用它this仍然引用顶层项而不是当前项。

登录到控制台项目是什么我可以看到父级总是在比第一级更深时引用链中的第一项(或不存在)。它会创建树,但对于除第一个之外的项目,对父项的引用将丢失。

var Item = function (item, parent) {
  console.log('item is :' + item.name);
  this.parent = parent;
  console.log('parent is: ' + parent);
  var fields = _.union(_.keys(item), _.keys(this.parent));
  _.each(_.without(fields, ['parent','children']), function (prop) {
    this[prop] = angular.isDefined(item[prop]) ? item[prop] : this.parent[prop];
  }, this);

  this.children = [];
  if (item.children) {
    this.children = _.map(item.children, function (child) {
      console.log('this is : ' + this);
      return new Item(child, this)
    }, this);
  }
};

var tree = new Item(root, {});

在制作小提琴时遇到一些麻烦,但这里有一些示例数据:

var root = JSON.parse('{"id":"1","name":"root item","root":"1","lft":"1","rgt":"22","level":"1","type":
"category","parent_id":"1","deadline":null,
"children":[
{"id":"2","name":"item 1","root":"1","lft":"14","rgt":"15","level":"2","type":"category","parent_id":"1"}, 
{"id":"6","name":"item 2","root":"1","lft":"16","rgt":"19","level":"2","type":"category","parent_id":"1"}, 
{"id":"10","name":"item 3","root":"1","lft":"20","rgt":"21","level":"2","type":"item","parent_id":"1"}]}');

2 个答案:

答案 0 :(得分:1)

它为我做的工作。我稍微简化了代码并添加了孙项。看一看: http://jsfiddle.net/7QYQL/1/

<击>
var grandchild = {};
grandchild.name = 'grandchild';
var child = {};
child.name = 'child';
child.children = [];
child.children[0] = grandchild;
var root = {};
root.name = 'root';
root.children = [];
root.children[0] = child;

<击>

问题是_.without()采用列表而不是数组作为第二个参数。

_.without(fields, 'parent','children')

这个有效: http://jsfiddle.net/eRbhm/13/

答案 1 :(得分:1)

问题在于您使用_.without method。要排除的元素作为可变数量的参数传递,而不是作为数组传递。

错误用法:

_.without(['a','b'],['a'])

结果为['a', 'b'](不是您想要的)

鉴于:

_.without(['a','b'],'a')

产生预期结果:['b']

这是修复的updated fiddle

注意:为了避免循环引用,我在“Result”输出中打印出parent.id而不是parent