我正在尝试创建一个函数,它将生成一个类似树的结构,这样每个项目都包含对它的父项的引用.
我有一个在创建子项时调用自身但在使用它时遇到困难的函数,似乎一旦从内部调用它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 = …Run Code Online (Sandbox Code Playgroud)