Example of a circular reference in Javascript?

2019-01-13 17:18发布

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

8条回答
孤傲高冷的网名
2楼-- · 2019-01-13 17:54

Probably the shortest way to define a cyclic object.

a = {}; a.a = a;
查看更多
乱世女痞
3楼-- · 2019-01-13 18:05
window.onload = function() {
  hookup(document.getElementById('menu'));

  function hookup(elem) {
    elem.attachEvent( "onmouseover", mouse);

    function mouse() {
    }
  }
}

As you can see, the handler is nested within the attacher, which means it is closed over the scope of the caller.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-13 18:05

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()
查看更多
女痞
5楼-- · 2019-01-13 18:06

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);

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:

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();

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.

查看更多
Luminary・发光体
6楼-- · 2019-01-13 18:06

Or even simpler, an array "containing" itself. See example:

var arr = [];
arr[0] = arr;
查看更多
爷、活的狠高调
7楼-- · 2019-01-13 18:06

Or using ES6:

class Circular {
  constructor() {
    this.value = "Hello World";
    this.self = this;
  }
}

circular = new Circular();
查看更多
登录 后发表回答