当前位置: 动力学知识库 > 问答 > 编程问答 >

scope - iife javascript variable lifetime

问题描述:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: