Javascript中的循环引用示例? [英] Example of a circular reference in Javascript?

查看:419
本文介绍了Javascript中的循环引用示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果有人在javascript中有一个好的,工作的例子的循环引用?我知道这是非常容易做关闭,但是很难把我的大脑围绕这一点。

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.

感谢

推荐答案

创建循环引用的一个简单方法是在属性中引用一个对象:

A simple way to create a circular reference is to have an object that refers to itself in a property:

function Foo() {
  this.abc = "Hello";
  this.circular = this;
}

var foo = new Foo();
alert(foo.circular.circular.circular.circular.circular.abc);

此处 foo

对于闭包,这通常只是在范围内具有循环引用而不是作为某个对象的显式属性更隐含:

With closures this is usually more implicit, by just having the circular reference in scope, not as an explicit property of some object:

var circular;

circular = function(arg) {
  if (arg) {
    alert(arg);
  }
  else {
    // refers to the |circular| variable, and by that to itself.
    circular("No argument");
  }
}

circular("hello");
circular();

这里保存在 circular 中的函数循环变量,从而自身。它隐式保存对自身的引用,创建一个循环引用。即使 circular 现在超出作用域,它仍然从函数作用域引用。简单的垃圾收集器不会识别这个循环,并且不会收集函数。

Here the function saved in circular refers to the circular variable, and thereby to itself. It implicitly holds a reference to itself, creating a circular reference. Even if circular 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.

这篇关于Javascript中的循环引用示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆