问题描述:

This question already has an answer here:

  • How do JavaScript closures work?

    84 answers

网友答案:

It survives because there's still a reference to it in one of your HTMLElements.

When you attach that lambda to the button.onclick property, there is a reference to count inside the lambda.

So long as that HTMLElement survives, or that onclick property remains assigned to that lambda, then count will survive too.

网友答案:

That's called a "closure".

Your function refers to display and count in its body, so it will "capture" those variables and "keep them alive" as long as it itself is alive (which it will here because you attached it to the DOM as an event handler).

相关阅读:
Top