Javascript weird closure behavior

I played (read: studied) using Javascript and came across something of my understanding, it seems very strange. This is due to the closing and link, which, apparently, "weakens" its importance for the browser.

The browser I use is Chromium 5.0.307.7 .

Anyway, here is the code:

HTMLElement.prototype.writeInSteps = function() {
  var i = 0;
  var elem = this;
  var args = arguments;

  function step() {
    elem.innerHTML += args[i];

    if(i < args.length) {
      i += 1;
    } else {
      elem.innerHTML = "";
      i = 0;
    }


    setTimeout(step, 500);
  }

  step();
}

What happens here is that the first argument is written to the correct HTMLElement, but all the rest are not written after that. It seems that after the first argument, the following arguments are written to some other element, which is now referenced by "elem".

It should also be mentioned that this only happens when I write something immediately after calling this function, for example:

div.writeInSteps("This", " is", " not", " working");
$id("body").innerHTML += "Doh!";

- , .

:

HTMLElement.prototype.writeInSteps = function() {
  var i = 0;
  var e = this.id;
  var args = arguments;

  function step() {
    var elem = $id(e);
    elem.innerHTML += args[i];

    if(i < args.length) {
      i += 1;
    } else {
      elem.innerHTML = "";
      i = 0;
    }


    setTimeout(step, 500);
  }

  step();
}

. : ?

: "... - ..." ntownsend. , , , .

+3
3

, DOM, JavaScript.

, - , . , innerHTML ( , ), , , , DOM. .

+3

innerHTML elem ( body, ), elem . step elem, , elem , - .

, , , elem, , .

0

, setTimeout(step, 500); , this - step , , HTMLElement.prototype.writeInSteps.step()?

( writeInSteps ). , , .

, . innerHTML , ( ).

-2

Source: https://habr.com/ru/post/1733529/


All Articles