我想要一个 javascript 类,将其子级映射到children.
这是我到目前为止得到的:
export default class Item {
constructor (id, name, children = []) {
this.id = id;
this.name = name;
this.children = children.map((child)=>{
return new Item(child.id, child.name, child.children)
});
}
test(){
console.log("Test");
}
//...
}
如果我现在这样称呼:
let children = [
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'foobar', children: [
{id: 4, name: 'foo'},
{id: 5, name: 'bar'},
]},
];
let newItem = new Item (item.id, item.name, item.children)
我想我会得到这样的递归映射:
[
Item: { id: 1, name: 'foo' },
Item: { id: 2, name: 'bar' },
Item: { id: 3, name: 'foo', children: [ Item: { id: 4, name: 'foo'}, Item: { id: 5, name: 'bar'}] },
]
在这种情况下,我应该能够拜访test()任何孩子。
newItem.children.forEach((child){ child.test(); });
但这会抛出
_vm.child.test 不是一个函数
慕后森
相关分类