有人可以解释这个JavaScript自动执行功能吗? [英] Can someone explain this JavaScript auto executing function?

查看:78
本文介绍了有人可以解释这个JavaScript自动执行功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var foo = (function(){
  var x = 0;
  return function(){return x++;};
})()

为什么var x = 0表达式只能运行一次,这是我对此最大的误解.

Why the var x = 0 expression only runs once is my biggest misunderstanding about this.

推荐答案

您的代码:

var foo = (function(){
  var x = 0;
  return function(){return x++;};
})()

等效于以下代码:

function f(){
  var x = 0;
  return function(){return x++;};
}
var foo = f();

很容易看出,当您像这样分解它时,函数f()仅被调用一次.它定义x,然后返回在f本地作用域内 中定义的 new 函数.这个新函数通常称为匿名函数"(意味着它没有名称)或闭包".实际上,javascript中的 all 函数都是闭包"-无论它们是否命名.术语关闭"仅表示该函数保留对父函数范围中定义的变量的访问-即使在父函数退出后也是如此.

It's easy to see, when you break it up like this, that the function f() is only called once. It defines x, and then returns a new function that is defined inside the local scope of f. This new function is often called an "anonymous function" (meaning that it has no name) or a "closure". In truth, all functions in javascript are "closures" -- whether or not they are named. The term "closure" simply means that the function retains access to the variables that were defined in the parent function's scope -- even after the parent function has exited.

因此,现在foo包含从f返回的新函数(闭包).您可以随意调用foo()多次-每次调用x都会返回并在后递增.由于x存在于闭包的父作用域中,因此其值将在多次调用闭包时保持不变.

So now, foo contains the new function (the closure) that was returned from f. You can call foo() as many times as you like -- and each time you do, x will be returned and post-incremented. Since x exists in the closure's parent scope, its value will persist across multiple calls to the closure.

此外...一旦f()退出,现在没有其他代码可以访问x了-这基本上意味着x现在是闭包的私有数据".整齐吧?

What's more... no other code now has access to x once f() has exited -- this basically means that x is now the "private data" of the closure. Pretty neat huh?

这篇关于有人可以解释这个JavaScript自动执行功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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