我不明白封闭的例子 [英] I cannot understand the example of a closure

查看:82
本文介绍了我不明白封闭的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请让我了解关闭。
为什么计数器在第一个版本中有效,但在第二个版本中无效?

Please me to understand the closures. Why does the counter work in the first variant, but in the second version there is not?

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

console.log(counter());
console.log(counter());
console.log(counter());

计数器输出0,1,2

The counter outputs 0,1,2

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

console.log(counter()());
console.log(counter()());
console.log(counter()());

计数器输出0,0,0

The counter outputs 0,0,0

有什么区别?

推荐答案

在第一个示例中,您使用的是立即调用函数表达式。这是内联调用函数,并将结果函数分配给counter。每次调用counter()时,您都在调用范围内具有count变量的内部函数。

In the first example, you are using an Immediately Inovked Function Expression. This is calling the function inline and assigning the resultant function to counter. Each time you call counter() you are calling that inner function which has the count variable in scope.

第二个示例等效于

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

用这种方式编写时,很明显当您调用counter()时,您将返回一个 new 函数,该函数的作用域内的 count 变量

When you write it this way, it's clearer that every time you call counter(), you are returning a new function with the count variable in scope

您可以在第二个示例中执行等效操作,方法是将结果分配给变量并多次调用。

You could do the equivalent in the second example by assigning the result to a variable and calling that multiple times.

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

var counterObj = counter();

counterObj(); // returns 0
counterObj(); // returns 1
counterObj(); // returns 2

这篇关于我不明白封闭的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆