Javascript递归函数引用此

JPR*_*JPR 6 javascript tree recursion

我正在尝试创建一个函数,它将生成一个类似树的结构,这样每个项目都包含对它的父项的引用.

我有一个在创建子项时调用自身但在使用它时遇到困难的函数,似乎一旦从内部调用它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, {});
Run Code Online (Sandbox Code Playgroud)

得到一个小提琴有点麻烦,但这里有一些示例数据:

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"}]}');
Run Code Online (Sandbox Code Playgroud)

sin*_*law 1

问题出在你对_.without方法的使用上。要排除的元素作为可变数量的参数传递,而不是作为数组传递。

错误用法:

_.without(['a','b'],['a'])
Run Code Online (Sandbox Code Playgroud)

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

然而:

_.without(['a','b'],'a')
Run Code Online (Sandbox Code Playgroud)

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

这是修复的更新小提琴。

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