Javascript闭包 [英] Javascript Closures

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

问题描述

我还是困惑于JavaScript中的闭包的概念。我得到的关键是闭包是内部函数访问在母函数返回后的母函数内创建的变量的能力。
但是我仍然困惑为什么我们必须创建内部函数来保护局部变量,如果我们可以在函数中创建一个变量。

I'm quite still confused with the concept of closure in JavaScript. I get the point that closure is the ability of the inner function to access the variable created within its mother function after the mother function has returned. But I'm still confused why do we have to create inner function to protect the local variable if we could just create a variable inside the function?

推荐答案

我们需要创建一个内部函数,使外部函数中的变量在外部函数返回后存在。

We need to create an inner function so that the variables in the outer function have some existence after the outer function returns.

简单函数:

function f() {
  var x = 0;
  return ++x; // x=1
} // Once the function has exited then "x" no longer exists.

请注意,变量x只有活动程序从f()函数的开始流向结束。但是如果我们在一个内部函数中包含x,那么x就会和内部函数一样生效:

Note that the variable "x" is only "active" (alive, existent) when control of the program flows from the start of the "f()" function to the end of it. But if we enclose "x" in an inner function then x will live as long as the inner function does:

function g() {
  var x = 0;
  return function() {
    // Now "x" will live for as long as this function.
    return ++x;
  }
};
var counter = g();
counter(); // => 1
counter(); // => 2
counter(); // => 3

现在当我们调用g()时,我们得到另一个函数,只要该函数由变量引用。

Now when we call "g()" we get another function, and "x" is active for as long as that function is referenced by a variable.

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

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