好吧,大脑冻结..。我需要你帮我做这件事:
const a = {
val: 'a',
neighbor: d
}
const b = {
val: 'b',
neighbor: a
}
const c = {
val: 'c',
neighbor: b
}
const d = {
val: 'd',
neighbor: c
}
console.log('d: neighbor - > ', d.neighbor)
console.log('a: neighbor - > ', a.neighbor)
const a必须指向const d,但遗憾的是const d是在const a之后定义的。在大多数情况下,我可以将const a移到const d之后,但在这种情况下,const d需要在const c之后定义。我遗漏了什么……?谢谢
发布于 2019-02-02 00:04:47
您可以将neighbor属性定义为getter。吸气剂实际上是在检索对象的值时执行的函数,也就是说,此时已经定义了所有引用的对象。这样还可以保护neighbor属性不受意外更改的影响。
const a = {
val: 'a',
get neighbor () {return d;}
};
const b = {
val: 'b',
get neighbor () {return a;}
};
const c = {
val: 'c',
get neighbor () {return b;}
};
const d = {
val: 'd',
get neighbor () {return c;}
};
console.log('d: neighbor - > ' , d.neighbor);
console.log('a: neighbor - > ' , a.neighbor);
发布于 2019-02-01 23:40:11
声明没有“邻居”属性的所有对象,然后将其添加到单独的赋值中。
const a = {
val: 'a'
}
const b = {
val: 'b'
}
const c = {
val: 'c'
}
const d = {
val: 'd'
}
a.neighbor = d;
b.neighbor = a;
c.neighbor = b;
d.neighbor = c;https://stackoverflow.com/questions/54488524
复制相似问题