简体   繁体   English

javascript中的闭包混淆

[英]Confusion with Closure in javascript

I have this code. 我有这个代码。

<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>
</body>

The variable add is assigned the return value of a self invoking function. 变量add被分配了一个自调用函数的返回值。

Does this mean, every time add is called,only return of function is invoked not the whole function ? 这是否意味着每次调用add时,仅调用函数返回而不是整个函数?

If not,Can anyone please explain it? 如果没有,任何人都可以解释一下吗?

Yes, only the returned function inside the IIFE is called when the add() function is called. 是的,在调用add()函数时,只会调用IIFE内部返回的函数。

The IIFE is called on pageload when the parser encounters it during the execution phase, and returns the other function as a reference to be called later. 当解析器在执行阶段遇到页面加载时,将在页面加载调用IIFE,然后将另一个函数作为引用返回,以供稍后调用。

The only thing the outer IIFE is doing is keeping the counter variable inside it's own scope. 外部IIFE唯一要做的就是将counter变量保留在其自己的范围内。

IIFE == Immediately-invoked function expression IIFE == 立即调用的函数表达式

In the following code, you have a function that returns a function: 在下面的代码中,您有一个返回函数的函数:

var add = (function () {
    var counter = 0;
    return function () {
        return counter += 1;
    }
})();

The outer function is immediately executed. 外部函数将立即执行。 So, add is assigned to the inner function: 因此, add分配给内部函数:

function () {
    return counter += 1;
}

As you can see, the counter variable in the inner function refers to the context of the outer function (where counter is declared). 如您所见,内部函数中的counter变量引用外部函数的上下文 (声明了counter )。 This context is called closure and is still referenced in the inner function. 上下文称为closure ,并且仍在内部函数中引用。 So, JavaScript keeps this context alive. 因此,JavaScript使该上下文保持活动状态。

As @RobG points out, the internal JavaScript execution rules are more like: the identifier counter in the inner function is first resolved in the inner execution context. 正如@RobG指出的那样,内部JavaScript执行规则更像是:内部函数中的标识符counter首先在内部执行上下文中解析。 Since it isn't found there, the next object on the scope chain is searched, which is the outer execution context and counter is found there. 由于在此处找不到对象,因此将搜索作用域链上的下一个对象,即外部执行上下文,并在其中找到counter

So, by the magic of closure, the counter variable can still be accessed and changed when calling the inner function (using add ). 因此,通过关闭的魔力,调用内部函数(使用add )时仍可以访问和更改counter变量。

So, when calling add , you are executing the inner function, which is closing over counter . 因此,在调用add ,您正在执行内部函数,该函数正在counter上关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM