【问题标题】:Javascript recursive function reference thisJavascript递归函数参考this
【发布时间】:2013-12-12 03:44:56
【问题描述】:

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

我有一个在创建孩子时调用自身的函数,但我很难使用它,似乎一旦从内部调用它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"}]}');

【问题讨论】:

  • 只是一个错字,我一直在尝试并忘记在发布之前将其更改回来。在这里修好了,问题还是一样。
  • 你能用一些虚拟数据为此创建小提琴吗?
  • 当然,可能需要几分钟才能完成。谢谢。
  • 这是一个小提琴:jsfiddle.net/eRbhm/2

标签: javascript recursion tree


【解决方案1】:

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

错误用法:

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

导致['a', 'b'](不是你想要的)

鉴于:

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

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

这是带有修复程序的updated fiddle

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

【讨论】:

    【解决方案2】:

    它为我完成了这项工作。我稍微简化了代码并添加了孙项。看一看: 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/

    【讨论】:

    • 感谢并为此竖起大拇指。我尝试了您的第一个答案并且它有效,但我的代码仍然没有,我无法弄清楚您的代码与我正在做的事情有何根本不同。修复_.没有立即修复它,我完全忽略了它。
    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2010-10-04
    • 1970-01-01
    • 2016-07-22
    • 2022-01-18
    • 2021-02-19
    相关资源
    最近更新 更多