Пример циклической ссылки в JavaScript?

Если Вы хотели бы к , сохраняют разрывы строки, Вы могли бы попробовать:

function parse($text) {
    // Damn pesky carriage returns...
    $text = str_replace("\r\n", "\n", $text);
    $text = str_replace("\r", "\n", $text);

    // JSON requires new line characters be escaped
    $text = str_replace("\n", "\\n", $text);
    return $text;
}
46
задан MatthewJ 29 September 2009 в 15:55
поделиться

2 ответа

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.

54
ответ дан 26 November 2019 в 20:20
поделиться
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.

11
ответ дан 26 November 2019 в 20:20
поделиться
Другие вопросы по тегам:

Похожие вопросы: