1. Simple example
Let’s start with a classic mistake. There are several divs on the page. We want to bind an onclick method to them, so we have the following code
function outerFn () {
functioninnerFn ( ) {}}
document.write("Inner function
");
JavaScript allows developers to pass functions like any type of data, that is, internal functions in JavaScript are able to escape the external functions that define them.
There are many ways to escape. For example, you can assign an internal function to a global variable:
Inner functions can also have their own variables, which are restricted to the scope of the inner function:
Copy code
When there are multiple internal functions, unexpected closures are likely to occur. We define an increasing function, the increment of this function is 2
Copy code
function innerFn2() {
outerVar = 2;
document.write("Inner function 2t");
document.write("outerVar = " outerVar "
");
}
return { "fn1": innerFn1, "fn2": innerFn2 };
}
var fnRef = outerFn();
fnRef.fn1();
fnRef.fn2();
fnRef.fn1();
var fnRef2 = outerFn();
fnRef2.fn1();
fnRef2.fn2();
fnRef2.fn1();
4.解惑
现在我们可以回头看看开头写的例子就很容易明白为什么第一种写法每次都会alert 4了。
After reading this, everyone must have some understanding of closures like me. Of course, if you fully understand it, you need to understand the execution environment and scope chain of the function ^_^