Javascript 中循环引用的示例?
我想知道是否有人有一个很好的、有效的 javascript 循环引用示例?我知道用闭包来做到这一点非常容易,但我很难理解这一点。如果我能在 Firebug 中剖析一个例子,我将非常感激。
谢谢
I was wondering if anyone has a good, working example of a circular reference in javascript? I know this is incredibly easy to do with closures, but have had a hard time wrapping my brain around this. An example that I can dissect in Firebug would be most appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
创建循环引用的一个简单方法是让一个对象在属性中引用自身:
这里
foo
对象包含对其自身的引用。对于闭包,这通常更加隐式,仅在作用域中具有循环引用,而不是作为某个对象的显式属性:
这里保存在
circular
中的函数引用circular
变量,从而对其自身而言。它隐式地持有对自身的引用,从而创建了循环引用。即使circular
现在超出了范围,它仍然是从函数范围中引用的。简单的垃圾收集器不会识别此循环,也不会收集该函数。A simple way to create a circular reference is to have an object that refers to itself in a property:
Here the
foo
object contains a reference to itself.With closures this is usually more implicit, by just having the circular reference in scope, not as an explicit property of some object:
Here the function saved in
circular
refers to thecircular
variable, and thereby to itself. It implicitly holds a reference to itself, creating a circular reference. Even ifcircular
now goes out of scope, it is still referenced from the functions scope. Simple garbage collectors won't recognize this loop and won't collect the function.或者更简单,一个“包含”自身的数组。参见示例:
Or even simpler, an array "containing" itself. See example:
可能是定义循环对象的最短方法。
Probably the shortest way to define a cyclic object.
正如您所看到的,处理程序嵌套在附加程序中,这意味着它在调用方的范围内是封闭的。
As you can see, the handler is nested within the attacher, which means it is closed over the scope of the caller.
或者使用 ES6:
Or using ES6:
你可以这样做:
window.window...window
var Circle = {};圆.圆 = 圆;
var 圆 = [];圆[0] = 圆;或者circle.push(circle)
function Circle(){this.self = this}; var 圆 = new Circle()
You can do:
window.window...window
var circle = {}; circle.circle = circle;
var circle = []; circle[0] = circle; or circle.push(circle)
function Circle(){this.self = this}; var circle = new Circle()
打印
a
或b
将返回Circular
。Printing
a
orb
would returnCircular
.圆形并带有封闭件。
Circular and with a closures.